Java流分组并汇总多个字段 [英] Java stream group by and sum multiple fields

查看:16
本文介绍了Java流分组并汇总多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表 fooList

I have a List fooList

class Foo {
    private String category;
    private int amount;
    private int price;

    ... constructor, getters & setters
}

我想按类别分组,然后将金额和价格相加.

I would like to group by category and then sum amount aswell as price.

结果将存储在地图中:

Map<Foo, List<Foo>> map = new HashMap<>();

关键是 Foo 持有汇总的金额和价格,并带有一个列表作为所有具有相同类别的对象的值.

The key is the Foo holding the summarized amount and price, with a list as value for all the objects with the same category.

到目前为止,我已经尝试了以下方法:

So far I've tried the following:

Map<String, List<Foo>> map = fooList.stream().collect(groupingBy(Foo::getCategory()));

现在我只需要将字符串键替换为包含汇总金额和价格的 Foo 对象.这是我卡住的地方.我似乎找不到任何方法.

Now I only need to replace the String key with a Foo object holding the summarized amount and price. Here is where I'm stuck. I can't seem to find any way of doing this.

推荐答案

有点难看,但应该可以:

A bit ugly, but it should work:

list.stream().collect(Collectors.groupingBy(Foo::getCategory))
    .entrySet().stream()
    .collect(Collectors.toMap(x -> {
        int sumAmount = x.getValue().stream().mapToInt(Foo::getAmount).sum();
        int sumPrice= x.getValue().stream().mapToInt(Foo::getPrice).sum();
        return new Foo(x.getKey(), sumAmount, sumPrice);
    }, Map.Entry::getValue));

这篇关于Java流分组并汇总多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆