Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda to populate Map

I am trying to fill up a map with words and the number of their occurrences. I am trying to write a lambda to do it, like so:

Consumer<String> wordCount = word -> map.computeIfAbsent(word, (w) -> (new Integer(1) + 1).intValue());

map is Map<String, Integer>. It should just insert the word in the map as a key if it is absent and if it is present it should increase its integer value by 1. This one is not correct syntax-wise.

like image 575
Karl Avatar asked Sep 30 '26 09:09

Karl


2 Answers

You can't increment the count using computeIfAbsent, since it will only be computed the first time.

You probably meant:

map.compute(word, (w, i) -> i == null ? 1 : i + 1);
like image 56
assylias Avatar answered Oct 01 '26 22:10

assylias


This is what Collectors are for.

Assuming you have some Stream<String> words:

Map<String, Long> countedWords = words
    .collect(Collectors
        .groupingBy(
            Function.identity(),
            Collectors.counting());
like image 35
lexicore Avatar answered Oct 01 '26 23:10

lexicore