我有一个 Element
对象流,我需要根据相等性对其进行过滤。使用 .distinct()
似乎很容易,但我得到了异常结果。即使对象返回相等,它们也不会被 .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 的 distinct()
方法(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.
您是否适本地覆盖了 Element
类的 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--
关于java - 不被 Stream.distinct() 过滤的相等对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901661/