Java Stream distinct() Tutorial 🎯

beginner
24 min

Java Stream distinct() Tutorial 🎯

Welcome to the Java Stream distinct() tutorial! In this comprehensive guide, we'll explore the distinct() method, which is an essential tool for dealing with duplicate elements in a Stream. Let's dive in! 🐳

What is Java Stream distinct()? 📝

The distinct() method is used to eliminate duplicate elements from a Stream. It returns a new Stream that contains only unique elements based on the equals() method.

Prerequisites 💡

Before we get started, it's important to have a basic understanding of the following topics:

Using distinct() 🎯

To use the distinct() method, you simply call it on the Stream and pass no arguments. Let's see an example:

java
import java.util.Arrays; import java.util.stream.Stream; public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 2, 3, 4, 4, 5}; Stream<Integer> stream = Arrays.stream(numbers); Stream<Integer> distinctNumbers = stream.distinct(); distinctNumbers.forEach(System.out::println); } }

Output:

1 2 3 4 5

In the example above, we have an array of integers with duplicate values. By creating a Stream from the array and using the distinct() method, we obtain a new Stream containing only unique elements.

💡 Pro Tip:

The distinct() method processes the Stream only once, so it's an efficient way to remove duplicates.

Using distinct() with Custom Comparator 🎯

In some cases, you might need to compare elements based on a custom logic. In those situations, you can provide a custom Comparator to the distinct() method:

java
import java.util.Arrays; import java.util.Comparator; import java.util.stream.Stream; public class Main { public static void main(String[] args) { String[] names = {"Alice", "Bob", "Alice", "Charlie", "Eve", "Eve"}; Stream<String> stream = Arrays.stream(names); Comparator<String> caseInsensitiveComparator = Comparator.comparing(String::toLowerCase); Stream<String> distinctNames = stream.sorted(caseInsensitiveComparator).distinct(); distinctNames.forEach(System.out::println); } }

Output:

Alice Bob Charlie Eve

In the example above, we have an array of strings with duplicate names (case sensitive). By using a custom Comparator that converts all strings to lowercase, we can sort and remove duplicates effectively.

Quiz 💡

Quick Quiz
Question 1 of 1

What does the Java Stream distinct() method do?

And that's it for our Java Stream distinct() tutorial! With this knowledge, you can now effectively deal with duplicate elements in your Java projects. Happy coding! 🎉