Here's my try:
Stream.of(Map.entry(Stone.WHITE, countIntersectionsOfColor(intersectionsSurroundingTerritory, Stone.WHITE)),
Map.entry(Stone.BLACK, countIntersectionsOfColor(intersectionsSurroundingTerritory, Stone.BLACK)))
.max((entry1, entry2) -> {
if (entry1.getValue().equals(entry2.getValue())) return null;
else return Long.compare(entry1.getValue(), entry2.getValue());
})
.map(Map.Entry::getKey)
.orElse(lastPlay.getOppositeColor());
I have a Stream<Map<Stone, Long>>
, where Stone
is an enum.
In few words, I want the key of the map that has the largest value, but if the values are equal, then I want to return lastPlay.getOppositeColor()
which returns a Stone
value.
My idea is to make max
return null if they are equal, therefore I have an empty Optional
thus I return what passed to orElse
.
Obviously, my code doesn't work as the compare
method passed to has int
return type.
Does anyone know how can I implement this with streams?
question from:
https://stackoverflow.com/questions/65927860/given-a-stream-with-two-objects-i-want-to-get-the-max-but-if-they-are-equal-i 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…