Can We Apply distinct() on All Streams in Java?
Short answer: Yes, but with an important condition. You can apply distinct() on any Java stream, but it works correctly only when the elements can be compared for…
Short answer: Yes, but with an important condition.
You can apply distinct() on any Java stream, but it works correctly only when the elements can be compared for equality.
Where distinct() Works
With Primitive Streams
IntStream.of(10, 20, 10, 30)
.distinct()
.forEach(System.out::println);
Output
10
20
30
Works perfectly because primitives are compared by value.
With Object Streams
List<String> list = Arrays.asList("Java", "Python", "Java");list.stream()
.distinct()
.forEach(System.out::println);
Output
Java
Python
Works because String properly overrides equals() and hashCode().
Where It Can Fail or Give Unexpected Results
Custom Objects Without equals() and hashCode()
class Employee {
int id;
Employee(int id) {
this.id = id;
}
}List<Employee> list = Arrays.asList(
new Employee(1),
new Employee(1)
);list.stream()
.distinct()
.forEach(e -> System.out.println(e.id));
Output
1
1
Duplicates are not removed.
Reason
Java compares object references, not content, if equals() and hashCode() are not overridden.
How to Fix It
Override equals() and hashCode()
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee e = (Employee) o;
return id == e.id;
}public int hashCode() {
return Objects.hash(id);
}
Now distinct() will work correctly.
Important Interview Insight
distinct() uses a HashSet internally.
That means it depends on:
equals()
hashCode()
Key Takeaways
You can use distinct() on any stream
It works perfectly for primitives and built-in classes
For custom objects, you must override equals() and hashCode()
Otherwise duplicates will not be removed
Final interview line
You can apply distinct() on all streams, but its correctness depends on proper equality definition of elements