我有一个Element
对象流,我需要根据相等性进行过滤。这似乎很容易与.distinct()
但我得到异常的结果。即使对象返回相等,它们也不会被.distinct()
过滤。未被Stream.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
贵'Element'类覆盖'equals'? – k0ner
是的。我正在使用Apache EqualsBuilder。它确实返回正确,如上所示。 (Object obj){ if(obj == null){ return false; } if(obj == this){ return true; (obj.getClass()!= getClass()){ }返回false; } Element other =(Element)obj; 返回新的EqualsBuilder()。append(getName(),other.getName())。isEquals(); } – mkeathley
也 - 如果您运行此代码,将会得到'IllegalStateException'。 'collect'方法是终端操作 – k0ner