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]
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]
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]
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]
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)
Thanks for sharing :)