Logo

dev-resources.site

for different kinds of informations.

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

Published at
12/7/2024
Categories
java
interview
streams
distinct
Author
realnamehidden1_61
Categories
4 categories in total
java
open
interview
open
streams
open
distinct
open
Author
18 person written this
realnamehidden1_61
open
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.
streams Article's
30 articles in total
Favicon
How does Optional.ifPresent() differ from Optional.orElse()?
Favicon
Beyond the Basics: Mastering Streams in Node.JS
Favicon
The streaming bridges — A Kafka, RabbitMQ, MQTT and CoAP example
Favicon
Java Streams | What is the difference between sorted() and distinct() in streams?
Favicon
How to handle large file uploads in SvelteKit using streams
Favicon
Execução preguiçosa com Lambdas
Favicon
Руководство по Java 8 Stream API
Favicon
In Java how to create a custom ArrayList that doesn't allow duplicate? #Interview Question
Favicon
Why Set Doesn't Allow Duplicates in Java
Favicon
Optional Class in Java and its methods
Favicon
A Few About: Streams NodeJs (PT-BR)
Favicon
File reading in python
Favicon
Asynchronous Streams in C#: Effortless Async Data Processing
Favicon
Working with streams in Node.js
Favicon
Migrating to Phoenix Liveview Streams
Favicon
What is Java Stream and why does it exist?
Favicon
-
Favicon
Streams em Node.js para iniciantes (guia básico)
Favicon
From a data stream to the data warehouse
Favicon
Gentle Intro to Node Streams
Favicon
The Java `.boxed()` Method
Favicon
Request and Response Stream - Observations
Favicon
Getting a near-real-time view of a DynamoDB stream with Python
Favicon
Exploring Java Streams
Favicon
Service Worker Side Rendering (SWSR)
Favicon
Listening to payments (real-time) on your Stellar wallet
Favicon
Supporting Cross Node Interactive Queries In Kafka Streams
Favicon
Summing Java Streams Api
Favicon
Handling Slow Servers in NodeJS
Favicon
Java 8 Non ce n’est pas que les streams

Featured ones: