3

I am trying to group my stream and aggregate on several fields

i.e.

private class Row {
    private String sku;
    private int colA; // sum
    private int colB; // sum
    private int colC; // avg
}

Example

  sku   colA    colB    colC
 ---------------------------
ar5sg5h  4       3       4
sd6ad6d  2       5       3
ar5sg5h  6       5       6
sd6ad6d  5       6       3
sd6ad6d  3       7       3

Expected:

 sku    colA    colB    colC
---------------------------
ar5sg5h  10      8       5.0
sd6ad6d  10     18       3.0

I already have List<Row> rows, where I have intention to reduce rows with groupBy and aggregation of sum on colA and colB where as average on colC.

How can I achieve this with groupBy + multiple aggregation using Java-8 stream?

2
  • Can you also add few example with what you have and what is your expected output? Commented Mar 31, 2020 at 6:34
  • @miiiii Added to the question. Commented Mar 31, 2020 at 6:46

1 Answer 1

3

Are you looking to:

List<Row> result = rows.stream()
        .collect(Collectors.groupingBy(Row::getSku))
        .values().stream()
        .map(e -> new Row(e.get(0).getSku(),
                e.stream().mapToDouble(Row::getColA).sum(),
                e.stream().mapToDouble(Row::getColB).sum(),
                e.stream().mapToDouble(Row::getColC).average().getAsDouble()))
        .collect(Collectors.toList());

Note: the type int is not helpfull in your case, I would suggest to change it to double as the average is not int.

Outputs

Row(sku=sd6ad6d, colA=10.0, colB=18.0, colC=3.0)
Row(sku=ar5sg5h, colA=10.0, colB=8.0, colC=5.0)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.