如果我有一个列表列表:
List<List<Map<String, Object>>> myList = new ArrayList<>();
List<Map<String, Object>> e1 = new ArrayList<>();
e1.add(new HashMap<String, Object>(){{put("test", 1);}});
e1.add(new HashMap<String, Object>(){{put("test", 6);}});
List<Map<String, Object>> e2 = new ArrayList<>();
e2.add(new HashMap<String, Object>(){{put("test", 9);}});
e2.add(new HashMap<String, Object>(){{put("test", 2);}});
myList.add(e1);
myList.add(e2);
我希望能够对内部列表(myList
和e1
)中的整数求和,对e2
进行迭代,然后返回和列表:
List<Integer> result = [7, 11]
答案 0 :(得分:4)
您可以这样做:
List<Integer> result = myList.stream()
.map(list -> list.stream()
.flatMapToInt(map -> map.values()
.stream()
.mapToInt(i -> (int) i))
.sum())
.collect(Collectors.toList());
答案 1 :(得分:0)
这是更全球化的另一种选择, ernest_k 解决方案更好,更优雅,但这也许可以帮助您了解有关流的更多信息
BinaryOperator<Object> accumulator = (a, b) -> Double.parseDouble("" + a) + Double.parseDouble("" + b);
List sums = myList.stream().map((e) -> e.stream()
.map((content) -> content.values().stream().reduce(0, accumulator)).reduce(0, accumulator))
.collect(Collectors.toList());
System.out.println("sums \n"+sums);