Java stream group by and sum multiple fields

MatMat :

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.

The result will be stored in a map:

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

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()));

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.

Sweeper :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36520&siteId=1