Java stream group by and sum multiple fields

MatMat picture MatMat · Aug 28, 2018 · Viewed 17.7k times · Source

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.

Answer

Sweeper picture Sweeper · Aug 28, 2018

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