2

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 ?

2 Answers2

6

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

Vikas
  • 6,868
  • 4
  • 27
  • 41
1

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());
Naman
  • 27,789
  • 26
  • 218
  • 353