Collectors.counting() returns long values for each key in this method:
private static Map<Integer, Long> countDuplicates(HashSet<Card> cards) {
return cards.stream().collect(Collectors.groupingBy(Card::getRankNumber, Collectors.counting()));
}
Is there a way to cast or convert the resulting Map from Map<Integer, Long> to Map<Integer, Integer>?
Direct casting gives this exception:
Type mismatch: cannot convert from Map<Integer,Integer> to Map<Integer,Long>
Note: The implementation of my class guarantees that cards has five objects in it, so there is no chance of overflow.
Try the following:
private static Map<Integer, Integer> countDuplicates(HashSet<Card> cards) {
return cards.stream()
.collect(Collectors.groupingBy(Card::getRankNumber, Collectors.summingInt(x -> 1)));
}
Instead of Collectors.counting() use Collectors.summingInt(x -> 1) so that you get immediately the value as an Integer.
Another way to get Map<Integer, Integer> is to use toMap collector along with Integer::sum method reference as a merge function:
private static Map<Integer, Integer> countDuplicates(HashSet<Card> cards) {
return cards.stream()
.collect(Collectors.toMap(Card::getRankNumber, x -> 1, Integer::sum));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With