Sum values from Maps using streams and collect to List

2hardproblems :

If I have a list of lists:

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);

I want be able to iterate over myList sum the ints in the inner lists (e1 and e2) and return a list of the sums:

List<Integer> result = [7, 11]
ernest_k :

You can do this:

List<Integer> result = myList.stream()
        .map(list -> list.stream()
                        .flatMapToInt(map -> map.values()
                                                .stream()
                                                .mapToInt(i -> (int) i))
                        .sum())
        .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121861&siteId=1