【问题标题】:group a list using stream java [duplicate]使用流java对列表进行分组[重复]
【发布时间】:2018-04-19 00:16:53
【问题描述】:

我的列表如下所示:

列表

[{
type: "1"
price: 10.0
count: 2
},
type: "1"
price: 15.0
count: 3
},
type: "2"
price: 20.0
count: 2
},
type: "2"
price: 30.0
count: 3
}]

我需要对它进行分组,以便我只有两种类型(在这种情况下)。

输出:

[{
type: "1"
price: 25.0
count: 5
},
type: "2"
price: 50.0
count: 5
}]

因此,基本上,列表中的元素数量将等于唯一类型的数量。价格和计数等其他值将被求和。

我试过用这个 -

report.stream().collect(Collectors.groupingBy(x -> x.getStuffe));

但是,这给出了一个地图。我不需要地图,我需要列表。

我该怎么做?

【问题讨论】:

    标签: java arraylist


    【解决方案1】:

    尝试做类似的事情:

    if (<types of list are equal>) {
        //add other attributes together
    }
    

    【讨论】:

    • 不能用流做?
    【解决方案2】:

    为什么需要流?这很容易在循环、hashmap 聚合和最终转储值集合中完成。所有这些迭代本质上都是在流的引擎下完成的,所以它并不慢,只是更冗长。

    HashMap map = new HashMap();
    for(Item x: list){
      Item old = map.put(x.type, x);
      if(old!=null) {
        x.price += old.price;
        x.count += old.count;
      }
    }
    return new ArrayList(map.values());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 2021-11-16
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多