Junior
What is the purpose of the sorted() method in streams?
sobes.tech AI
Answer from AI
The sorted() method in Java Streams is used to create a stream with sorted elements. There are two overloads of this method:
-
sorted(): Sorts the elements in their natural order (for types that implementComparable).Stream<String> stringStream = Stream.of("banana", "apple", "cherry"); Stream<String> sortedStream = stringStream.sorted(); // Sorts alphabetically -
sorted(Comparator<? super T> comparator): Sorts the elements according to the providedComparator.Stream<Integer> intStream = Stream.of(5, 2, 8, 1); Stream<Integer> sortedStreamDesc = intStream.sorted(Comparator.reverseOrder()); // Sorts in descending order List<Person> people = Arrays.asList( new Person("Alice", 30), new Person("Bob", 25), new Person("Charlie", 35) ); Stream<Person> sortedPeopleByAge = people.stream().sorted(Comparator.comparingInt(Person::getAge)); // Sorts by age
The sorted() method is an intermediate operation in a stream. This means it returns a new stream and does not modify the original. Sorting is performed lazily during the execution of a terminal operation.