使用Java流从Guava表中提取统计信息

时间:2018-05-14 20:34:10

标签: lambda stream guava

给出番石榴桌Table <Integer, String, WeatherInformation>。我想打印使用Java 8按工作日分组的统计数据。

WeatherInformation类具有温度,雪和雨变量的getter方法。         平日工作日天气信息

    1   Sunday  Temperature=25, Snow=0, Rain=0

    2   Monday  Temperature=25, Snow=0, Rain=1

    3   Tuesday Temperature=25, Snow=0, Rain=2

    4   Sunday  Temperature=25, Snow=0, Rain=3

    5   Monday  Temperature=25, Snow=0, Rain=4

    6   Friday  Temperature=25, Snow=0, Rain=5

    7   Saturday Temperature=25, Snow=0, Rain=6

    8   Sunday  Temperature=25, Snow=0, Rain=7

    9   Monday  Temperature=25, Snow=0, Rain=8

Print:
Sunday = Count:3, Avg[Temp:25; Snow:0; Rain:3.33]
Monday = Count:3, Avg[Temp:25; Snow:0; Rain:4.33]
Tuesday = Count:1, Avg[Temp:25; Snow:0; Rain: 6]
Friday = Count: 1, Avg[Temp:25; Snow:0; Rain: 5]
Saturday = Count: 1, Avg[Temp:25; Snow:0; Rain: 6]

1 个答案:

答案 0 :(得分:0)

您必须最终汇总平均数据,所以我的想法是将您的天气信息累积到持有人类中,最后您可以打印任何统计数据

public static void transform(Table<Integer, String, WeatherInformation> data) {
    Map<String, WeatherInformationStats> result =
            data.cellSet().stream()
                .collect(groupingBy(Cell::getColumnKey,
                                    mapping(Cell::getValue,
                                            reducing(new WeatherInformationStats(),
                                                     WeatherInformationStats::of,
                                                     WeatherInformationStats::plus))));
    // Here you're able to do whatever you want with your cumulative data
    // The data look line: Sunday -> {temperature: 12, snow: 10, rain: 7, count: 3}
}

@Data
public static class WeatherInformation {
    protected int temperature;
    protected int snow;
    protected int rain;

    // Getter/setter
}

@Data
public static class WeatherInformationStats extends WeatherInformation {
    protected int count;

    // Getter setter

    public static WeatherInformationStats of(WeatherInformation source) {
        WeatherInformationStats ws = new WeatherInformationStats();
        ws.setTemperature(source.getTemperature());
        ws.setSnow(source.getSnow());
        ws.setRain(source.getRain());
        ws.setCount(1);
        return ws;
    }

    public WeatherInformationStats plus(WeatherInformationStats source) {
        temperature += source.getTemperature();
        snow += source.getSnow();
        rain += source.getRain();
        count += source.getCount();
        return this;
    }
}