How to apply groupby->mapping->reducing in Java 8 stream

I am having List of below object.

public class Sample {
    private String driver;
    private String vehicle;
    private Double score;
    private Integer time;
}

My data would look like below.

enter image description here

I am trying to groupBy driver and then apply map function(mentioned in the above table) and then reduce to Map with key as driver and value as map function’s result(which is of type Double). I have tried below

list.stream().collect(Collectors.groupingBy(o-> o.getDriverId(),
            Collectors.mapping()
            ));

But not able to apply the map function. Please give some inputs to proceed further.

Answer

Try this:

Map<String, Double> res =
    list.stream()
        .collect(groupingBy(Sample::getDriver,
                            collectingAndThen(
                                reducing(new Sample("", "", 0.0,0),
                                         (a, b) -> new Sample("", "", a.score + b.score * b.time, a.time + b.time)), 
                                         s -> s.score / s.time)));

Leave a Reply

Your email address will not be published. Required fields are marked *