DEV Community

realNameHidden
realNameHidden

Posted on

5 1 2 1 1

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (1)

Collapse
 
programmerraja profile image
Boopathi

Thanks for sharing :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay