简体   繁体   中英

Get the sum of values from a HashMap where the keys have matches in a List of Strings with streams

I have a Map<String, Long> which looks like this: first = {"A": 20, "B": 50, "C": 100} and a List second = {"A","M","B"}.

What I need to do is find the keys which have matching String values in the second List, and form a List with the corresponding values from the Map. So, I need to get: third = 70 because the keys "A" and "B" are also in the list and their values are 20 and 50. I want to achieve this with Streams and so far, I have this, where I find the list of String of matchingSymbols, but I need to get the sum of values:

List<String> matchingSymbols = first.entrySet()
                .stream()
                .flatMap(incrementProgression -> second.stream().filter(incrementProgression.getKey()::equals))
                .collect(Collectors.toList());

Can anyone help me?

Stream over the list ( second ), rather than the map. Map each element of the list by querying the map. If an element is not in the map, the result will be null, so we remove those elements with a filter . Finally, we can do a sum :

long third = second.stream()
        .map(first::get)
        .filter(Objects::nonNull)
        .mapToLong(x -> x)
        .sum();

Here is one way to do it.

Map<String, Long> m = Map.of("A", 20L, "B", 50L, "C", 100L);
List<String> list = List.of("A", "M", "B");
  • ensure a value for the key exists
  • get the values
  • sum them
long sum = list.stream().filter(m::containsKey).mapToLong(m::get)
        .sum();

System.out.println(sum);

prints

70

You could solve it like this:

Map<String, Long> first = Map.of("A", 20L, "B", 50L, "C", 100L);
List<String> second = List.of("A", "M", "B");

long sum = second.stream() //stream tokens you search
        .mapToLong(key -> first.getOrDefault(key, 0L)) //get the corresponding value from the map, use 0 as default
        .sum(); //get the sum

System.out.println(sum);

Instead of iterating over the Map first and checking if they exist in the map, you can more easily iterate over the token list second , get the corresponding value from the map and sum them up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM