簡體   English   中英

Java 8流 - 合並地圖並計算“值”的平均值

[英]Java 8 stream - Merge maps and calculate average of “values”

假設我有一個類List ,每個類都有一個Map

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

Map中的Long鍵是時間戳, Integer值是得分。

我正在嘗試創建一個Stream ,它可以組合來自所有對象的Map ,並輸出具有唯一時間戳(The Long s)和平均分數的Map

我有這個代碼,但它給了我所有分數的總和而不是平均值Integer類沒有平均方法)。

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

有可能嗎?

而不是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())
            )
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM