Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

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:

  1. Call distinct() on a stream to filter out duplicates.
  2. It uses equals() and hashCode() for comparison.
  3. Follow it with a terminal operation like collect() or forEach().

πŸ“₯ 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() and hashCode() 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.