Multiple aggregate functions in Java 8 Stream API

前端 未结 4 1462
甜味超标
甜味超标 2021-02-08 14:17

I have a class defined like

public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}
4条回答
  •  甜味超标
    2021-02-08 14:25

    Assuming that your TimePeriodCalc class has all the necessary getters, this should get you the list you want:

    List result = new ArrayList<>(
        list.stream()
        .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate, 
            Collectors.collectingAndThen(Collectors.toList(), TimePeriodCalc::avgTimePeriodCalc)))
        .values()
    );
    

    Where TimePeriodCalc.avgTimePeriodCalc is this method in the TimePeriodCalc class:

    public static TimePeriodCalc avgTimePeriodCalc(List list){
        return new TimePeriodCalc(
                list.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getOccupancy)),
                list.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getEfficiency)),
                list.get(0).getAtDate()
                );
    }
    

    The above can be combined into this monstrosity:

    List result = new ArrayList<>(
        list.stream()
        .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate, 
            Collectors.collectingAndThen(
                Collectors.toList(), a -> {
                    return new TimePeriodCalc(
                            a.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getOccupancy)),
                            a.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getEfficiency)),
                            a.get(0).getAtDate()
                            );
                }
            )))
        .values());
    

    With input:

    List list = new ArrayList<>();
    list.add(new TimePeriodCalc(10,10,"a"));
    list.add(new TimePeriodCalc(10,10,"b"));
    list.add(new TimePeriodCalc(10,10,"c"));
    list.add(new TimePeriodCalc(5,5,"a"));
    list.add(new TimePeriodCalc(0,0,"b"));
    

    This would give:

    TimePeriodCalc [occupancy=7.5, efficiency=7.5, atDate=a]
    TimePeriodCalc [occupancy=5.0, efficiency=5.0, atDate=b]
    TimePeriodCalc [occupancy=10.0, efficiency=10.0, atDate=c]
    

提交回复
热议问题