Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream group by and sum multiple fields

Tags:

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.

like image 212
MatMat Avatar asked Aug 28 '18 12:08

MatMat


1 Answers

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));
like image 181
Sweeper Avatar answered Sep 23 '22 02:09

Sweeper