问题
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