The distinct() method in Java is used to remove duplicate elements from a stream. It returns a new stream containing only unique elements based on the equals() and hashCode() methods.
- It is an intermediate operation, meaning it returns a stream and does not produce a final result by itself.
- For ordered streams, the order of elements is preserved.
- For unordered streams, the order of distinct elements is not guaranteed.
- It is a stateful operation because it keeps track of previously seen elements.
Example:
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 1, 2, 2, 3);
list.stream().distinct().forEach(System.out::println);
}
}
Output
1 2 3
Explanation:
- stream() converts the list into a stream.
- distinct() removes duplicate elements using equals() and hashCode().
- forEach() prints each unique element.
Syntax
Stream<T> distinct()
Example 1: This program demonstrates how to use the Stream.distinct() method in Java to remove duplicate elements from a stream.
import java.util.*;
class GFG {
public static void main(String[] args) {
List<String> list = Arrays.asList(
"Geeks", "for", "Geeks", "GeeksQuiz", "for", "GeeksforGeeks");
list.stream().distinct().forEach(System.out::println);
}
}
Output
Geeks for GeeksQuiz GeeksforGeeks
Explanation:
- distinct() filters out duplicate strings using equals() and hashCode().
- forEach(System.out::println) prints each unique element from the stream.
Example 2: This program counts the number of distinct elements in a list using the Stream.distinct() method
import java.util.*;
class GFG {
public static void main(String[] args) {
List<String> list = Arrays.asList(
"Geeks", "for", "Geeks", "GeeksQuiz", "for", "GeeksforGeeks");
long count = list.stream().distinct().count();
System.out.println(count);
}
}
Output
4
Explanation: count() returns the total number of unique elements in the stream.