Java 8 Stream distinct is not working -
this doing:
list scores = stream.concat(oldentries.stream(), newentries.stream()) .sorted() .distinct() .limit(maxsize) .collect(collectors.tolist());
i expecting sorted list without duplicates, times there duplicate in list.
i have override hashcode , equals method, have observed these methods returning correct value every time. can 1 see wrong stream?
this equals() , hashcode() auto generated idea :
.. private int userid; private int levelid; private int score; @override public boolean equals(object o) { if (this == o) return true; if (o == null || getclass() != o.getclass()) return false; score score = (score) o; if (userid != score.userid) return false; return levelid == score.levelid; } @override public int hashcode() { int result = userid; result = 31 * result + levelid; return result; } public int compareto(score other) { if (other == null) { return 1; } else { return integer.compare(other.score, this.score); } } ..
your stream first ordered according compareto
, i.e. using score
.
it's "distinctified" using equals()
, i.e. using userid
, levelid
. according javadoc:
for ordered streams, selection of distinct elements stable (for duplicated elements, element appearing first in encounter order preserved.) unordered streams, no stability guarantees made.
example:
score 1, user 2, level 3 score 3, user 2, level 3 score 1, user 3, level 1
after sorting...
score 1, user 2, level 3 score 1, user 3, level 1 score 3, user 2, level 3
distinct nothing, because elements not equal according user/level. can result in "duplicate" elements, because you're ordering stream based on 1 thing, determining equality entirely different thing.
Comments
Post a Comment