How to find the sum of values of map whose key contains the given prefix?

I have a method with the following signature:

int sum(Map<String, Integer> map, String target) { }

I am trying to find the sum of values of the entries who key has the prefix as the given target string. I want to do this using streams. This is what I’ve done:

return map.entrySet().stream()
    .filter((k, v) -> k.startsWith(target))
    .map((k, v) -> v)
    .sum();

Compiler gives the following error:

error: incompatible types: incompatible parameter types in lambda expression

What am I doing wrong here?

Answer

Map’s entrySet returns a Set<Map.Entry<K, V>>.

Use Entry’s getKey and getValue to access the key and value and use mapToInt and sum.

map.entrySet().stream()
        .filter(entry -> entry.getKey().startsWith(target))
        .mapToInt(Map.Entry::getValue)
        .sum();

Leave a Reply

Your email address will not be published. Required fields are marked *