Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort object using java 8 streams

I am using the stream API in java 8 to handle my collections. However, I am wondering what would be an elegant way to sort my objects in a given order, using this API.

SortedCollection = inputCollection.stream()
    .map(e -> {
        return new Element(e.id, e.color);
    }).collect(Collectors.toList());

Here I would like to sort the elements that have been mapped, using the id attribute.

Any idea ? Thanks !

like image 224
E. Bavoux Avatar asked Feb 02 '18 15:02

E. Bavoux


People also ask

How do you sort objects using streams?

Stream sorted() in Java Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed.

What is the purpose of sorted method of stream in Java 8?

sorted. Returns a stream consisting of the elements of this stream, sorted according to natural order. If the elements of this stream are not Comparable , a java. lang.


1 Answers

Simply use Stream#sorted as follows with the name of your getter method for the Element's ID.

inputCollection.stream()
               .map(e -> new Element(e.id, e.color))
               .sorted(Comparator.comparing(Element::getId))
               .collect(Collectors.toList());
like image 164
Jacob G. Avatar answered Oct 29 '22 19:10

Jacob G.