Karl
Karl

Reputation: 223

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.

Upvotes: 2

Views: 217

Answers (3)

assylias
assylias

Reputation: 328598

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);

Upvotes: 7

Andrew
Andrew

Reputation: 49606

It doesn't compile because you can't call a method on a primitive:

new Integer(1) -> 1  // unboxing was applied
(1 + 1).intValue()   // incorrect

I would write it with Map#put and Map#getOrDefault:

Consumer<String> consumer = word -> map.put(word, map.getOrDefault(word, 0) + 1);

Upvotes: 2

lexicore
lexicore

Reputation: 43661

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());

Upvotes: 2

Related Questions