Java 8 stream group by with multiple aggregation

Pratik :

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?

YCF_L :

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)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374523&siteId=1