Java – counts objects with the same attribute value

I'm creating a poker ranking solution. I have to count cards of the same suit or the same ranking in a set of cards Here I create a HashMap and add values if multiple queues are in the collection

private boolean isFourOfAKind() {
        Map<RANK,Integer> rankDuplicates = new HashMap<>();
        for(Card card : cards) {
            rankDuplicates.put(card.getRank(),rankDuplicates.getOrDefault(card.getRank(),0) + 1);
        }
        return rankDuplicates.containsValue(4);
    }

I wonder if it's possible to use streams exactly the same thing as Java streams It looks like this:

private boolean isFourOfAKind() {
        Map<RANK,Integer> rankDuplicates = cards.stream()
            .map(Card::getRank)
            .collect(Collectors.toMap(/*...something goes here..*/)); // of course this is very wrong,but you can see what I'm aiming at.
        return rankDuplicates.containsValue(4);
    }

Solution

Looks like you're looking for something similar

return cards.stream()
        .collect(Collectors.toMap(Card::getRank,e -> 1,Integer::sum))
        //                        keyMapper,valueMapper,mergeFunction
        .containsValue(4);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>