【问题标题】:Get the sum of values from a HashMap where the keys have matches in a List of Strings with streams从 HashMap 中获取值的总和,其中键在带有流的字符串列表中匹配
【发布时间】:2022-01-16 21:06:51
【问题描述】:

我有一个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());

谁能帮帮我?

【问题讨论】:

    标签: java java-stream


    【解决方案1】:

    流过列表 (second),而不是地图。通过查询地图来映射列表的每个元素。如果元素不在地图中,则结果将为空,因此我们使用filter 删除这些元素。最后,我们可以做一个sum

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

    【讨论】:

      【解决方案2】:

      这是一种方法。

      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
      

      【讨论】:

        【解决方案3】:

        你可以这样解决:

        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 中,您可以更轻松地遍历令牌列表 second,从 map 中获取相应的值并将它们相加。

        【讨论】:

          猜你喜欢
          • 2018-10-29
          • 1970-01-01
          • 2015-06-23
          • 1970-01-01
          • 1970-01-01
          • 2022-12-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多