Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
}
like image 970
user6811616 Avatar asked Sep 01 '18 13:09

user6811616


People also ask

How do you sort an ArrayList of objects in Java 8?

– Use Collections. sort() method for sorting the ArrayList in-place, or Java 8 Stream. sorted() to return a new sorted ArrayList of Objects (the original List will not be modified). – For Descending order, just pass Collections.

Can you use streams with primitives Java?

Streams primarily work with collections of objects and not primitive types. Fortunately, to provide a way to work with the three most used primitive types – int, long and double – the standard library includes three primitive-specialized implementations: IntStream, LongStream, and DoubleStream.


2 Answers

You may do it like so,

List<DateRange> sortedList = listToBeSorted.stream()
    .sorted(Comparator.comparingInt(DateRange::getStartRange))
    .collect(Collectors.toList());
like image 110
Ravindra Ranwala Avatar answered Nov 15 '22 10:11

Ravindra Ranwala


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));
like image 22
fps Avatar answered Nov 15 '22 08:11

fps