I have a stream of Element
objects that I needed to filter based on equality. This seems easy enough with .distinct()
but I was getting abnormal results. Even though the objects return as equal they are not filtered by .distinct()
.
What am I missing? Proof below --
List<Element> elements = getStream().filter(e -> e.getName().equals("userId")).collect(Collectors.toList());
System.out.println("Elements with same name: " + elements.size());
if(elements.size() > 1) {
System.out.println("Equals?: " + elements.get(0).equals(elements.get(1)));
}
System.out.println("Distinct Elements: " + getStream().distinct().count());
System.out.println("Full Elements: " + getStream().count());
Outputs:
Elements with same name: 2
Equals?: true
Distinct Elements: 8
Full Elements: 8
Java Stream distinct() MethodThe elements are compared using the equals() method. So it's necessary that the stream elements have proper implementation of equals() method. If the stream is ordered, the encounter order is preserved.
distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable. But, in case of unordered streams, the selection of distinct elements is not necessarily stable and can change.
To find an element matching specific criteria in a given list, we: invoke stream() on the list. call the filter() method with a proper Predicate. call the findAny() construct, which returns the first element that matches the filter predicate wrapped in an Optional if such an element exists.
According to the distinct()
method of the Stream API (http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--):
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
Do you override equals()
and hashCode()
of the Element
class appropriately?
http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object- http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With