【问题标题】:Find Sum of Map Items in List of Map在地图列表中查找地图项的总和
【发布时间】:2022-12-05 17:23:00
【问题描述】:

我有List<Map<String,Integer>>

列表中的每个项目都由地图项目组成,如下所示(仅用于表示)

List[0].Map[0]("Sam",10)
        Map[1]("Sarah",12)
        Map[2]("Remi", 18)

List[1].Map[0]("Darren",13)
        Map[1]("Peter",19)
        Map[2]("Larry", 21)

有没有办法检查大于 50 的地图总和并获取列表的索引。

Output : 1 , as items in Map on List[1] exceeds 50

我可以通过多个 for 循环获得我需要的东西,但是有更好的方法吗?

【问题讨论】:

    标签: java


    【解决方案1】:

    要查找地图列表中地图项的总和并获取总和超过某个值的列表的索引,可以使用 List 和 Map 类的 stream() 和 filter() 方法,以及Stream 类的 reduce() 和 sum() 方法。

    以下是如何使用这些方法解决问题的示例:

    // Create a List of Maps
    List<Map<String,Integer>> listOfMaps = new ArrayList<>();
    
    // Add some maps to the list
    listOfMaps.add(Map.of("Sam", 10, "Sarah", 12, "Remi", 18));
    listOfMaps.add(Map.of("Darren", 13, "Peter", 19, "Larry", 21));
    
    // Use the stream() and filter() methods to find the index of the list where the sum of the map items is greater than 50
    int index = listOfMaps.stream()
        .filter(map -> map.values().stream().reduce(0, Integer::sum) > 50)
        .findFirst()
        .map(listOfMaps::indexOf)
        .orElse(-1);
    
    // Print the index
    System.out.println("Index: " + index);
    

    在此示例中,代码使用 stream() 方法从列表创建地图流,并使用 filter()

    【讨论】:

      猜你喜欢
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2021-12-17
      • 1970-01-01
      相关资源
      最近更新 更多