Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

java - Given a stream with two objects, I want to get the max, but if they are equal I want null

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...