有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用流计算值的百分比

我试图弄清楚如何在使用stream时计算列表中特定值的百分比

我的对象getTag可以取值GY,我想计算列表中G:s的百分比。另一个对象是getDateTime,其形式为1946-01-12

我有条件filter(weather -> !weather.getDateTime().isAfter(dateTo) && !weather.getDateTime().isBefore(dateFrom)),因为我只需要用户输入的两个日期之间的百分比

因此,每个DateTime值对应于GY。我使用Collectors.counting()来计算GY的频率,但是我如何得到百分比呢

Map<String, Long> percentage = weatherData.stream()
        .filter(weather -> !weather.getDateTime().isAfter(dateTo) && !weather.getDateTime().isBefore(dateFrom))
        .collect(Collectors.groupingBy(Weather::getTag, Collectors.counting()));

共 (1) 个答案

  1. # 1 楼答案

    如果您将所关心的项目(“G”)映射为1,将其他所有项目映射为0,则平均值为流中“G”的百分比

    double pctG = list.stream()
        .mapToInt(obj -> obj.getTag().equals("G") ? 1 : 0)
        .summaryStatistics()
        .getAverage();
    

    使用Java 13,您可以使用teeing()收集器按标记计数元素,过滤后的元素总数,最后将组计数除以总数:

    Map<String, Double> fractions = weatherData.stream()
            .filter(...)
            .collect(
                Collectors.teeing(
                    Collectors.groupingBy(Weather::getTag, Collectors.counting()),
                    Collectors.counting(),
                    YourClass::scale));
    

    其中scale()函数将每组除以总数:

    static <T> Map<T, Double> scale(Map<? extends T, Long> counts, long total) {
        return counts.entrySet().stream().
            .collect(Collectors.toMap(e -> e.getKey(), ((double) e.getValue()) / total));
    }