Java 8 Stream not working

This is what I do:

List scores = Stream.concat(oldEntries.stream(), newEntries.stream())
                    .sorted()
                    .distinct()
                    .limit(maxSize)
                    .collect(Collectors.toList());

I expect a sorted list without any duplicates, but sometimes there is a duplicate in the list.

I override the hashCode and equals method. I also noticed that these methods return the correct value every time. Can anyone see what is wrong with my flow?

These are my equals () and hashCode (). They are automatically generated by 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);
    }
}

 ..
+4
source share
1 answer

Your stream is first ordered according to compareTo, that is, with score.

Then it is "different" with equals(), that is, with userIdand levelId. According to javadoc:

( , , .) .

:

score 1, user 2, level 3
score 3, user 2, level 3
score 1, user 3, level 1

...

score 1, user 2, level 3
score 1, user 3, level 1
score 3, user 2, level 3

Distinct , /. "" , , .

+7

Source: https://habr.com/ru/post/1685528/


All Articles