聚合另一个对象内的Map对象

时间:2019-12-03 21:53:58

标签: java dictionary

编辑版本!通过PC而不是手机。 我定义了一个具有以下属性的类:

这是我在不属于另一个类的情况下用于示例Map的代码:

    List<Map<String,Long>> amountList = new ArrayList<>();
    Map<String, Long> amountMap = new HashMap<>();

    for(int i=0; i<2;i++ ) {
        amountMap.put("AMOUNT1", 12L);
        amountMap.put("AMOUNT2", 10L);
        amountMap.put("AMOUNT3", 10L);
        amountMap.put("AMOUNT4", 12L);
        amountMap.put("AMOUNT5", 10L);
        amountList.add(amountMap);
    }

    Map<String, Long> collectset = amountList.stream()
            .flatMap(entry -> entry.entrySet().stream())
            .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum));

    for (String str : collectset.keySet()){
        System.out.println( "output: " + str + " -> " + collectset.get(str));
    }

我需要从中得到的结果如下所示:

output: AMOUNT3 -> 20
output: AMOUNT2 -> 20
output: AMOUNT1 -> 24
output: AMOUNT5 -> 20
output: AMOUNT4 -> 24

由于上面的代码,我得到的是这些值重复两次。 有没有办法只输出一次Sum等效项。例如,如果将循环更改为生成5张地图-我看到输出被打印了5次。

2 个答案:

答案 0 :(得分:0)

创建一个包含三个字符串的信息对象,并将其用作键值(如果需要,请不要忘记覆盖hashCode)。或者只是使用一种格式(例如CSV)来将您的字符串混合在一起,然后将该字符串用作键。

答案 1 :(得分:0)

我能够找到问题。在Stream实施之前有一个for循环,它导致根据我在循环中循环的次数来打印输出。

这是更新的代码:

    List<Map<String,Long>> countList = new ArrayList<>();
    Map<String, Long> countMap = new HashMap<>();

    Random random = new Random();

    for(int i=0; i<500;i++ ) {
        countMap.put("COUNT" + random.nextInt(10), 12L);
        countMap.put("COUNT" + random.nextInt(10), 10L);
        countMap.put("COUNT" + random.nextInt(10), 10L);
        countMap.put("COUNT" + random.nextInt(10), 12L);
        countMap.put("COUNT" + random.nextInt(10), 10L);
        countList.add(countMap);
    }

    Map<String, Long> collectset = countList.stream()
            .flatMap(entry -> entry.entrySet().stream())
            .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum));

    System.out.println( "CollectSet Size: " + collectset.size());
相关问题