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<String>
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?
Solution 1:
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();
Solution 2:
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