Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a HashMap<Integer, Long> ito HashMap<Integer, Integer>

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.

like image 882
Reid Moffat Avatar asked May 01 '26 09:05

Reid Moffat


2 Answers

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.

like image 65
dreamcrash Avatar answered May 03 '26 21:05

dreamcrash


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));
}
like image 31
Nowhere Man Avatar answered May 03 '26 21:05

Nowhere Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!