Sorting a collection with the Java 8 Streams API means converting the collection to a stream, applying the sorted() intermediate operation, and collecting the result back into a new collection. It offers a fluent alternative to Collections.sort() without mutating the original list.
Key Points: • sorted() with no arguments sorts elements using their natural ordering, which requires the elements to implement Comparable. • sorted(Comparator) accepts a custom comparator for sorting by a specific field or in reverse order. • The stream pipeline does not modify the source collection; sorting produces a new stream. • collect(Collectors.toList()) (or toSet(), toMap(), etc.) is used to materialize the sorted stream back into a collection. • Comparator.comparing() combined with thenComparing() lets you build multi-field sort criteria concisely.
Example: Given a list of Employee objects, employees.stream().sorted(Comparator.comparing(Employee::getSalary)).collect(Collectors.toList()) returns a new list ordered by ascending salary without touching the original list.
Code Example:
List<String> names = Arrays.asList("Charlie", "Alice", "Bob");
List<String> sorted = names.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(sorted); // [Alice, Bob, Charlie]Interview Tip: A concise interview answer is:
"I convert the collection to a stream, call sorted() with either natural ordering or a custom Comparator, and then collect the results with Collectors.toList(). Unlike Collections.sort(), this doesn't mutate the original collection, and Comparator.comparing().thenComparing() makes multi-field sorting easy to express."