1

Why is the sorted() method on Stream not named sort()?

list.stream().sort()
  • 2
    Probably because it returns a sorted copy of the list instead of sorting it in place. – Becuzz Sep 5 '17 at 18:45
5

According to the documentation, the sorted() method is a stateful intermediate operation.

You can read more about what that means here:

Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.

So sorted() describes the new stream created by the sorted() method, not the act of sorting.

  • 4
    The grammar makes sense but is inconsistent with map, filter, etc. I guess it's a legitimate question to ask why there is that discrepancy. – Solomonoff's Secret Sep 5 '17 at 19:47
  • I guess the main reason is that there is already an interface with a sort method in the JRE, and that sort method sorts in-place. Having a lazy, non-destructive method also called sort would be confusing. – Jörg W Mittag Sep 6 '17 at 5:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.