java使用流计算值的百分比
我试图弄清楚如何在使用stream
时计算列表中特定值的百分比
我的对象getTag
可以取值G
或Y
,我想计算列表中G:s
的百分比。另一个对象是getDateTime
,其形式为1946-01-12
我有条件filter(weather -> !weather.getDateTime().isAfter(dateTo) && !weather.getDateTime().isBefore(dateFrom))
,因为我只需要用户输入的两个日期之间的百分比
因此,每个DateTime值对应于G
或Y
。我使用Collectors.counting()
来计算G
和Y
的频率,但是我如何得到百分比呢
Map<String, Long> percentage = weatherData.stream()
.filter(weather -> !weather.getDateTime().isAfter(dateTo) && !weather.getDateTime().isBefore(dateFrom))
.collect(Collectors.groupingBy(Weather::getTag, Collectors.counting()));
# 1 楼答案
如果您将所关心的项目(“G”)映射为1,将其他所有项目映射为0,则平均值为流中“G”的百分比
使用Java 13,您可以使用
teeing()
收集器按标记计数元素,和过滤后的元素总数,最后将组计数除以总数:其中
scale()
函数将每组除以总数: