DEV Community

realNameHidden
realNameHidden

Posted on

Java Streams | What is the difference between sorted() and distinct() in streams?

For Explanation watch video

sorted()

The sorted() method is used to sort the elements of a stream. It orders the elements based on their natural ordering or a custom comparator.

Key Characteristics:

Returns a sorted stream of elements.
Does not eliminate duplicates (it retains all elements).
Can use natural ordering or a custom comparator.

Example 1: Natural Ordering

List<Integer> numbers = List.of(4, 2, 3, 1, 4);
List<Integer> sortedList = numbers.stream()
                                  .sorted()
                                  .collect(Collectors.toList());
System.out.println(sortedList); // Output: [1, 2, 3, 4, 4]

Enter fullscreen mode Exit fullscreen mode

Example 2: Custom Ordering

List<String> names = List.of("Charlie", "Alice", "Bob");
List<String> sortedNames = names.stream()
                                .sorted((a, b) -> b.compareTo(a)) // Reverse order
                                .collect(Collectors.toList());
System.out.println(sortedNames); // Output: [Charlie, Bob, Alice]

Enter fullscreen mode Exit fullscreen mode

2. distinct()

The distinct() method is used to remove duplicate elements from a stream. It retains only unique elements based on the result of their equals() method.

Key Characteristics:

  • Eliminates duplicates from the stream.
  • Retains the original order of elements (stable).
  • Relies on the implementation of equals() for determining uniqueness.

Example: Removing Duplicates

List<Integer> numbers = List.of(4, 2, 3, 1, 4);
List<Integer> distinctList = numbers.stream()
                                    .distinct()
                                    .collect(Collectors.toList());
System.out.println(distinctList); // Output: [4, 2, 3, 1]

Enter fullscreen mode Exit fullscreen mode

Example Combining sorted() and distinct()

You can use both methods together to first remove duplicates and then sort the remaining elements.

List<Integer> numbers = List.of(4, 2, 3, 1, 4);
List<Integer> result = numbers.stream()
                              .distinct() // Remove duplicates
                              .sorted()   // Sort the unique elements
                              .collect(Collectors.toList());
System.out.println(result); // Output: [1, 2, 3, 4]

Enter fullscreen mode Exit fullscreen mode

When to Use Each?

  • Use sorted() when you want to order the elements in a specific sequence.
  • Use distinct() when you want to ensure there are no duplicates in your stream.
  • Both methods can be combined when your use case requires removing duplicates and sorting the resulting elements.

Top comments (1)

Collapse
 
programmerraja profile image
Boopathi

Thanks for sharing :)