本文介绍了Java8:从列表到地图收集最小值,最大值和平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Integres列表,并希望从列表到地图获取最小值,最大值和平均值.下面是我的代码,

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);

但是我想要在Stream迭代中得到它,

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 ?

推荐答案

您可能想使用IntSummaryStatistics

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

然后,您可以在统计信息上使用get方法.您可以使用IntSummaryStatistics

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

这篇关于Java8:从列表到地图收集最小值,最大值和平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:20