从 HashMap 获取值的总和,其中键在带有流的字符串列表中匹配
Get the sum of values from a HashMap where the keys have matches in a List of Strings with streams
我有一个 Map<String, Long>
看起来像这样:
first = {"A": 20,
"B": 50,
"C": 100}
和一个List<String>
second = {"A","M","B"}.
我需要做的是在第二个List中找到匹配String值的键,并用Map中对应的值组成一个List。所以,我需要得到:
third = 70
因为键“A”和“B”也在列表中,它们的值是 20 和 50。我想用 Streams 实现这个,到目前为止,我有这个,我可以在其中找到字符串列表的匹配符号,但我需要得到值的总和:
List<String> matchingSymbols = first.entrySet()
.stream()
.flatMap(incrementProgression -> second.stream().filter(incrementProgression.getKey()::equals))
.collect(Collectors.toList());
谁能帮帮我?
流过列表 (second
),而不是地图。通过查询地图来映射列表的每个元素。如果某个元素不在地图中,则结果将为空,因此我们使用 filter
删除这些元素。最后,我们可以做一个 sum
:
long third = second.stream()
.map(first::get)
.filter(Objects::nonNull)
.mapToLong(x -> x)
.sum();
你可以这样解决:
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);
无需遍历 Map first
并检查它们是否存在于 map 中,您可以更轻松地遍历 token 列表 second
,从 map 中获取相应的值并将它们相加向上。
这是一种方法。
Map<String, Long> m = Map.of("A", 20L, "B", 50L, "C", 100L);
List<String> list = List.of("A", "M", "B");
- 确保键值存在
- 获取值
- 求和
long sum = list.stream().filter(m::containsKey).mapToLong(m::get)
.sum();
System.out.println(sum);
打印
70
我有一个 Map<String, Long>
看起来像这样:
first = {"A": 20,
"B": 50,
"C": 100}
和一个List<String>
second = {"A","M","B"}.
我需要做的是在第二个List中找到匹配String值的键,并用Map中对应的值组成一个List。所以,我需要得到:
third = 70
因为键“A”和“B”也在列表中,它们的值是 20 和 50。我想用 Streams 实现这个,到目前为止,我有这个,我可以在其中找到字符串列表的匹配符号,但我需要得到值的总和:
List<String> matchingSymbols = first.entrySet()
.stream()
.flatMap(incrementProgression -> second.stream().filter(incrementProgression.getKey()::equals))
.collect(Collectors.toList());
谁能帮帮我?
流过列表 (second
),而不是地图。通过查询地图来映射列表的每个元素。如果某个元素不在地图中,则结果将为空,因此我们使用 filter
删除这些元素。最后,我们可以做一个 sum
:
long third = second.stream()
.map(first::get)
.filter(Objects::nonNull)
.mapToLong(x -> x)
.sum();
你可以这样解决:
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);
无需遍历 Map first
并检查它们是否存在于 map 中,您可以更轻松地遍历 token 列表 second
,从 map 中获取相应的值并将它们相加向上。
这是一种方法。
Map<String, Long> m = Map.of("A", 20L, "B", 50L, "C", 100L);
List<String> list = List.of("A", "M", "B");
- 确保键值存在
- 获取值
- 求和
long sum = list.stream().filter(m::containsKey).mapToLong(m::get)
.sum();
System.out.println(sum);
打印
70