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 !
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With