Sobes.tech
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:

  1. sorted(): Sorts the elements in their natural order (for types that implement Comparable).

    Stream<String> stringStream = Stream.of("banana", "apple", "cherry");
    Stream<String> sortedStream = stringStream.sorted(); // Sorts alphabetically
    
  2. sorted(Comparator<? super T> comparator): Sorts the elements according to the provided Comparator.

    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.

What is the purpose of the sorted() method in… - sobes.tech