Get Distinct Elements

distinct() is an intermediate Stream API operation that filters out duplicate elements, keeping only the first occurrence of each unique value based on equals().

Key Points: • distinct() uses each element's equals() and hashCode() implementation to determine uniqueness. • For custom objects, equals()/hashCode() must be properly overridden, otherwise distinct() falls back to reference equality. • It's a stateful operation - it must track everything seen so far, which uses O(n) extra memory. • The relative encounter order of the retained elements is preserved for ordered streams. • On unordered parallel streams, distinct() may perform better since strict order preservation isn't required.

Example: Given the list [1, 2, 2, 3, 3, 3], calling distinct() produces a stream yielding just 1, 2, 3.

Code Example:

List<Integer> distinctNumbers = numbers.stream()
        .distinct()
        .collect(Collectors.toList());

Interview Tip: A concise interview answer is:

"distinct() removes duplicate elements from a stream based on their equals()/hashCode() implementation, keeping the first occurrence in encounter order. For custom objects it only works correctly if equals() and hashCode() are properly overridden."