Java 8 stream - merge maps and calculate average "values"

Say I have Listclasses, each of which has Map.

public class Test {
    public Map<Long, Integer> map;
}

The keys Longin Mapare timestamps, and the values Integerare grades.

I am trying to create Streamone that can combine cards with all objects and output Mapwith unique timestamps ( Longs) and an average score.

I have this code, but it gives me the sum of all the indicators, not the average (the class Integerdoes not have an average method).

Test test1 = new Test();
    test1.map = new HashMap() {{
        put(1000L, 1);
        put(2000L, 2);
        put(3000L, 3);
    }};

    Test test2 = new Test();
    test2.map = new HashMap() {{
        put(1000L, 10);
        put(2000L, 20);
        put(3000L, 30);
    }};

    List<Test> tests = new ArrayList() {{
        add(test1);
        add(test2);
    }};

    Map<Long, Integer> merged = tests.stream()
            .map(test -> test.map)
            .map(Map::entrySet)
            .flatMap(Collection::stream)
            .collect(
                    Collectors.toMap(
                            Map.Entry::getKey,
                            Map.Entry::getValue,
                            Integer::sum

                    )
            );
    System.out.println(merged);

, , Stream, Map List . .

Map<Long, List<Integer>> 

?

+4
1

Collectors.toMap Collectors.groupingBy:

Map<Long, Double> merged = tests.stream()
        .map(test -> test.map)
        .map(Map::entrySet)
        .flatMap(Collection::stream)
        .collect(
                Collectors.groupingBy(
                        Map.Entry::getKey,
                        Collectors.averagingInt(Map.Entry::getValue)
                )
        );

, , Map<Long, List<Integer>>, , :

Map<Long, List<Integer>> merged = tests.stream()
    .map(test -> test.map)
    .map(Map::entrySet)
    .flatMap(Collection::stream)
    .collect(
            Collectors.groupingBy(
                    Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())
            )
    );
+5

Source: https://habr.com/ru/post/1690055/


All Articles