Java 8 streams group by 3 fields and aggregate by sum and count produce single line output

Viewed 21829

I know there a similar questions asked in the forum but none of them seem to be addressing my problem fully. Now I'm very new to Java 8, so please bear with me. I have a list of Products, for example:

Input:
name    category    type    cost
prod1       cat2     t1      100.23
prod2       cat1     t2      50.23
prod1       cat1     t3      200.23
prod3       cat2     t1      150.23
prod1       cat2     t1      100.23


Output:
Single line (name, category, type) summing the cost and count of products.




Product {
    public String name;
    public String category;
    public String type;
    public int id;
    public double cost;

}

I need to group this by name, category and type and produce a single result that summarizes this data and produces the total cost and count of each product. Most examples show grouping by two fields and aggregating using single criteria.

Following suggestions on the forumn, i came up with this for groupings:

    public class ObjectKeys {

    ArrayList<Object> keys;

    public ObjectKeys(Object...searchKeys) {

         keys = new ArrayList<Object>();

            for (int i = 0; i < searchKeys.length; i++) {
                keys.add( searchKeys[i] );
            }
    }

}

Then used it as follows:

Map<String, Map<String, Map<String, List<Product>>>> productsByNameCategoryType =
    products.stream().collect(groupingBy(new ObjectKeys(l.name(), l.category(),l.type())))

But how do I chain count and sum to the the above code? Especially for group by with more than 2 fields. Is there a better way to do this?

Like I mentioned my Java8 is not that good, please help.

2 Answers
Related