Java 8 FAQ: Top Questions
21. How does the distinct() method work in Java 8 Streams?
The distinct()
method in Java 8 Streams is used to remove duplicate elements from a stream. It uses the equals()
method of objects to determine uniqueness and works on both object and primitive streams.
πΊοΈ Step-by-Step Instructions:
- Call
distinct()
on a stream to filter out duplicates. - It uses
equals()
andhashCode()
for comparison. - Follow it with a terminal operation like
collect()
orforEach()
.
π₯ Example Input:
List words = Arrays.asList("apple", "banana", "apple", "orange", "banana");
π Expected Output:
[apple, banana, orange]
β Java 8 Solution:
import java.util.*;
import java.util.stream.*;
public class DistinctExample {
public static void main(String[] args) {
List words = Arrays.asList("apple", "banana", "apple", "orange", "banana");
List uniqueWords = words.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueWords);
}
}
π Detailed Explanation:
- distinct(): Filters out duplicate elements using
equals()
. - Only works properly if the objects implement
equals()
andhashCode()
correctly. - Maintains the encounter order of the stream.
π οΈ Use Cases:
- Removing duplicates from a collection during stream processing.
- Pre-cleaning lists for further transformation or aggregation.
- Extracting unique records for reporting or display.