I used to use the following line to sort elements before streams showed up in Java:
Collections.sort(collection, new CustomComparator());
Now I found out that I can get the same result by doing:
collection.stream().sorted(new CustomComparator());
In both cases I use a list and a custom comparator that implements Comparator
(I need this and cannot implement it on the class itself).
I haven't found anything that indicates that they are different in any way, except for the fact that the stream solution looks nicer.
Is there any advantage to use the stream version? I mean... is it more performant? Is there any difference?
collection.stream().sorted(new CustomComparator())
doesn't sort the collection
, only makes the stream sorted.
To achieve a similar result with Stream API, you should use a terminal operation - collect into a new list:
collection.stream().sorted(new CustomComparator()).collect(Collectors.toList());
It won't modify the original collection (the stream source), but Collections.sort
will.
I would make a copy of the collection and do sorting on it, in case the original order matters.
List<?> collectionCopy = new ArrayList(collection);
Collections.sort(collectionCopy, new CustomComparator());
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