Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any advantage to use stream().sorted() over Collection.sort()?

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?

like image 759
Sebastian D'Agostino Avatar asked Apr 27 '18 19:04

Sebastian D'Agostino


1 Answers

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());
like image 118
Andrew Tobilko Avatar answered Nov 14 '22 21:11

Andrew Tobilko