未被 Stream.distinct() 过滤的相等对象
Equal Objects not being filtered by Stream.distinct()
我有一个 Element
对象流,需要根据相等性进行过滤。使用 .distinct()
这似乎很容易,但我得到了异常结果。即使对象 return 相等,它们也不会被 .distinct()
过滤。
我错过了什么?下面证明 --
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());
输出:
Elements with same name: 2
Equals?: true
Distinct Elements: 8
Full Elements: 8
根据 Stream API (http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--) 的 distinct()
方法:
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
您是否适当地覆盖了 Element
class 的 equals()
和 hashCode()
?
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--
我有一个 Element
对象流,需要根据相等性进行过滤。使用 .distinct()
这似乎很容易,但我得到了异常结果。即使对象 return 相等,它们也不会被 .distinct()
过滤。
我错过了什么?下面证明 --
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());
输出:
Elements with same name: 2
Equals?: true
Distinct Elements: 8
Full Elements: 8
根据 Stream API (http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--) 的 distinct()
方法:
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
您是否适当地覆盖了 Element
class 的 equals()
和 hashCode()
?
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--