27

How to find the maximum, minimum, sum and average of the numbers in the following list in Java 8?

List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
DrJava
  • 379
  • 1
  • 3
  • 4
  • 5
    You can do it by writing an application. What have you tried so far? – BackSlash Sep 23 '14 at 06:53
  • Here is all you need: http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html – micha Sep 23 '14 at 06:55
  • What following list? Did you intend to post some code? – Duncan Jones Sep 23 '14 at 06:55
  • any list doe snot matter – DrJava Sep 23 '14 at 06:56
  • @DrJava So a list of strings would be suitable? I suspect not. – Duncan Jones Sep 23 '14 at 06:57
  • 2
    Did the OP get a badge for this question? First time I've seen a question with -8 that has an answer with +29 – Adam Aug 03 '17 at 09:06
  • 1
    @Adam the OP got [this badge](https://stackoverflow.com/help/badges/28/famous-question?userid=4017219) which is not connected to the votes. The constellation you’ve commented does not make the questioner deserve a badge, but the *answerer* got [this badge](https://stackoverflow.com/help/badges/95/reversal?userid=2097529) and since the question’s score has turned positive since you’ve commented, the answerer also got [this badge](https://stackoverflow.com/help/badges/8842/lifeboat?userid=2097529). – Holger Jan 27 '21 at 14:03

3 Answers3

127

There is a class name, IntSummaryStatistics

For example:

List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream()
                                     .mapToInt((x) -> x)
                                     .summaryStatistics();
System.out.println(stats);

Output:

IntSummaryStatistics{count=10, sum=129, min=2, average=12.900000, max=29}

Read about IntSummaryStatistics

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • 1
    Not an obvious, yet a very fine answer. I like that `IntSummaryStatistics` thing. – Krzysztof Jabłoński Oct 27 '14 at 18:40
  • 6
    I find it tells a lot about java when you see a line like `.mapToInt((x) -> x)` – njzk2 May 14 '15 at 18:31
  • 2
    to anyone using any form of modern language, this seems like a dirty hack, or at best a useless piece of code to make the compiler happy. (in this case I would probably rather use `map(myIntSummaryStatistics::accept)` though, as the convertion to intstream feels really weird) – njzk2 May 14 '15 at 20:12
  • @njzk2 I like to use Integer::valueOf in such cases ;) – Line Feb 01 '19 at 22:03
13

I think it's always good to know more than one solution to a problem to pick the right that suits the problem the most. Here are some other solutions:

final List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);

Find the maximum

// MAX -- Solution 1
primes.stream() //
    .max(Comparator.comparing(i -> i)) //
    .ifPresent(max -> System.out.println("Maximum found is " + max));

// MAX -- Solution 2
primes.stream() //
    .max((i1, i2) -> Integer.compare(i1, i2)) //
    .ifPresent(max -> System.out.println("Maximum found is " + max));

// MAX -- Solution 3
int max = Integer.MIN_VALUE;
for (int i : primes) {
    max = (i > max) ? i : max;
}
if (max == Integer.MIN_VALUE) {
    System.out.println("No result found");
} else {
    System.out.println("Maximum found is " + max);
}

// MAX -- Solution 4 
max = Collections.max(primes);
System.out.println("Maximum found is " + max);

Find the minimum

// MIN -- Solution 1
primes.stream() //
    .min(Comparator.comparing(i -> i)) //
    .ifPresent(min -> System.out.println("Minimum found is " + min));

// MIN -- Solution 2
primes.stream() //
    .max(Comparator.comparing(i -> -i)) //
    .ifPresent(min -> System.out.println("Minimum found is " + min));

// MIN -- Solution 3
int min = Integer.MAX_VALUE;
for (int i : primes) {
    min = (i < min) ? i : min;
}
if (min == Integer.MAX_VALUE) {
    System.out.println("No result found");
} else {
    System.out.println("Minimum found is " + min);
}

// MIN -- Solution 4
min = Collections.min(primes);
System.out.println("Minimum found is " + min);

Find the average

// AVERAGE -- Solution 1
primes.stream() //
    .mapToInt(i -> i) //
    .average() //
    .ifPresent(avg -> System.out.println("Average found is " + avg));

// AVERAGE -- Solution 2
int sum = 0;
for (int i : primes) {
    sum+=i;
}
if(primes.isEmpty()){
    System.out.println("List is empty");
} else {
    System.out.println("Average found is " + sum/(float)primes.size());         
}

Find the sum

// SUM -- Solution 1
int sum1 = primes.stream() //
    .mapToInt(i -> i) //
    .sum(); //
System.out.println("Sum found is " + sum1);

// SUM -- Solution 2
int sum2 = 0;
for (int i : primes) {
    sum2+=i;
}
System.out.println("Sum found is " + sum2);

But be as consice as possible, so my favourites are:

// Find a maximum with java.Collections
Collections.max(primes);

// Find a minimum with java.Collections 
Collections.min(primes);

By the way, Oracle Tutorial is a golden mine: https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html

KeyMaker00
  • 6,194
  • 2
  • 50
  • 49
3
    //By using lambda
    int sum = primes.stream().mapToInt(a->a).sum();
    System.out.println(sum);
    int min = primes.stream().mapToInt(a->a).min().orElse(0);
    System.out.println(min);
    int max = primes.stream().mapToInt(a->a).max().orElse(0);
    System.out.println(max);
    double average = primes.stream().mapToInt(a->a).average().orElse(0);
    System.out.println(average);
    
    //By using Collections
    System.out.println(Collections.min(primes));
    System.out.println(Collections.max(primes));
Kuresh
  • 31
  • 1
  • 3
    You will need to explain why your solution solves the problem. The main item of your answer is the idea. The code is merely an illustration. – Lajos Arpad Nov 10 '20 at 12:47