Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equal Objects not being filtered by Stream.distinct()

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
like image 644
mkeathley Avatar asked Nov 24 '15 18:11

mkeathley


People also ask

Does stream distinct use equals?

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.

How do I use distinct in stream?

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.

How do I get one object from a stream list?

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.


1 Answers

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--

like image 188
Rafael Naufal Avatar answered Oct 23 '22 12:10

Rafael Naufal