How can I use Java 8 streams to sort an ArrayList of objects by a primitive int member?
Asked Answered
H

2

8

Here is an example class. I know the simplest thing would be to change the members from primitive type int to object Integer and use stream/lambda/sorted, but there may be reasons to only have a primitive type int such as space. How could I use the streams API to sort a List<DateRange> by int member startRange?

List<DateRange> listToBeSorted = new ArrayList<DateRange>();


static private class DateRange
{
    private int startRange ;
    private int endRange ;
    public int getStartRange() {
        return startRange;
    }
    public void setStartRange(int startRange) {
        this.startRange = startRange;
    }
    public int getEndRange() {
        return endRange;
    }
    public void setEndRange(int endRange) {
        this.endRange = endRange;
    }
}
Hexyl answered 1/9, 2018 at 13:23 Comment(2)
note compareTo will not work with primitive types. It requires an ObjectHexyl
there is at least a 16 byte overhead to having two Integers instead of two primitive int membersHexyl
C
5

You may do it like so,

List<DateRange> sortedList = listToBeSorted.stream()
    .sorted(Comparator.comparingInt(DateRange::getStartRange))
    .collect(Collectors.toList());
Concatenation answered 1/9, 2018 at 14:9 Comment(0)
D
3

I know you asked for a way to do it with streams, but if you are OK with sorting the original list in-place, you don't need streams for this. Just use the List.sort method:

listToBeSorted.sort(Comparator.comparingInt(DateRange::getStartRange));
Dexterdexterity answered 2/9, 2018 at 3:22 Comment(2)
Much more efficient.Mastoiditis
Both of these are helpful thanks. In the case above I purposely made a copy of the List because I am iterating through the sorted list while modifying the original list.Hexyl

© 2022 - 2024 — McMap. All rights reserved.