Java8: Collect min, max and avg from List to Map [duplicate]

邮差的信 提交于 2020-11-29 02:50:44

问题


I have List of Integres and want get min, max and avg from list to Map. Below is my code,

List<Integer> numbers = Arrays.asList(-2, 1, 2, 3, 5, 6, 7, 8, 9, 10, 100);

int min = numbers.stream().mapToInt(n -> n).min().getAsInt();
int max = numbers.stream().mapToInt(n->n).max().getAsInt();
double avg = numbers.stream().mapToInt(n->n).average().getAsDouble();

Map<String, Number> result = new HashMap<>();
result.put(“min”, min);
result.put(“max”, max);
result.put(“avg”, avg);

But what I want is to get this in Stream iteration,

numbers.stream().mapToInt(n->n).collect(toMap/* Map with min, max and average*/ ));

Is there any way to achieve this ?


回答1:


You may want to use IntSummaryStatistics,

IntSummaryStatistics stats = numbers.stream()
                .mapToInt(n -> n)
                .summaryStatistics();

Then you can use get methods on stats. You can get count, min, max, avg, and sum with IntSummaryStatistics




回答2:


You can use IntSummaryStatistics to collect all such stats.

IntSummaryStatistics summaryStats = numbers.stream().mapToInt(n -> n).summaryStatistics();

and then consume them to create the Map as:

Map<String, Number> result = new HashMap<>();
result.put("min", summaryStats.getMin());
result.put("max", summaryStats.getMax());
result.put("avg", summaryStats.getAverage());


来源:https://stackoverflow.com/questions/58888565/java8-collect-min-max-and-avg-from-list-to-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!