Find maximum, minimum, sum and average of a list in Java 8
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
get List from with maximum and minimum sum from (nested List) List of List using Java 8
You can use this:
List<Competitor> minListCompetitor = anotherListOfListCompetitor.stream()
.min(Comparator.comparingInt(l -> l.stream().mapToInt(Competitor::getPower).sum()))
.orElse(Collections.emptyList());
List<Competitor> maxListCompetitor = anotherListOfListCompetitor.stream()
.max(Comparator.comparingInt(l -> l.stream().mapToInt(Competitor::getPower).sum()))
.orElse(Collections.emptyList());
This returns the .min()
/ .max()
of the sum from the lists. It uses a simplified version of the code you provided to calculate the sum.
If you want to throw an exception if no maximum is found you can use .orElseThrow()
.
how to get the sum, average, minimum and maximum of five numbers-java using do-while loop
The best way to handle the min/max values is to keep track of them as your read in each value:
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i=0; i < 5; ++i) {
num = scan.nextInt();
if (num > max) max = num;
if (num < min) min = num;
sum += num;
}
double average = sum / 5.0d;
I seed the max and min values with the smallest/largest integer values, respectively. This lets us capture the actual min and max values as they are read in. Also, I think that a basic for
loop works better here than a do
while loop.
Note that I compute the average using a double type, because it may not be a pure integer value (even in your sample data the average is not an integer).
Java 8 Stream: average and count at once
Use summaryStatistics()
:
DoubleSummaryStatistics stats = products.stream()
.mapToDouble(this::timeConsumingCalculateRating)
.filter(rating -> rating > 0.0D)
.summaryStatistics();
long count = stats.getCount();
double averageRating = stats.getAverage();
Finding out min, max, avg, sum in ArrayList
that's because you set min
to be 0
and it is lower than all values.
you need to initialize it to a large number (say Integer.MAX_VALUE
) then it will work
Calculating average of an array list?
Why use a clumsy for loop with an index when you have the enhanced for loop?
private double calculateAverage(List <Integer> marks) {
Integer sum = 0;
if(!marks.isEmpty()) {
for (Integer mark : marks) {
sum += mark;
}
return sum.doubleValue() / marks.size();
}
return sum;
}
Update:
As several others have already pointed out, this becomes much simpler using Streams with Java 8 and up:
private double calculateAverage(List <Integer> marks) {
return marks.stream()
.mapToDouble(d -> d)
.average()
.orElse(0.0)
}
Finding max, min, sum, and average of n amount of values using for loop
Here is a nicer way to do this, which doesn't even require storing all the numbers at once. The approach here is to keep a running tab on the largest and smallest input, as each new number is input. Also, we maintain a running total of all numbers entered, which later easily can be used to compute the average.
Scanner scanner = new Scanner(System.in);
double max, min, avg;
double total = 0.0d;
boolean first = true;
int numbers = 12;
for (int i=0; i < numbers; ++i) {
System.out.println("Enter number:");
double d = scanner.nextDouble();
if (first) {
max = d;
min = d;
total = d;
first = false;
}
else {
if (d > max) {
max = d;
}
else if (d < min) {
min = d;
}
total += d;
}
}
avg = total / numbers;
System.out.println("max: " + max + ", min: " + min + ", avg: " + avg);
Note that a more advanced approach might be to do something like store all 12 numbers into a list, and then leverage the Java 8 stream API to find the max, min, and average. But I suspect that is not the answer you want for your question.
Finding min, max, avg in ArrayList
These kinds of calculations have gotten quite a bit easier with Java 8. Assuming you have the following wrapper class to wrap your data:
class Data {
final String name;
final int value;
public Data(String name, int value) {
this.name = name;
this.value = value;
}
}
You can now run:
Stream.of(new Data("Utah" ,5 ),
new Data("Nevada" ,6 ),
new Data("California" ,12),
new Data("Oregon" ,8 ),
new Data("Utah" ,9 ),
new Data("California" ,10),
new Data("Nevada" ,4 ),
new Data("Nevada" ,4 ),
new Data("Oregon" ,17),
new Data("California" ,6 ))
.collect(Collectors.groupingBy(
d -> d.name,
Collectors.summarizingInt(d -> d.value)))
.forEach((name, summary) -> System.out.println(name + ": " + summary));
Which yields:
Oregon: IntSummaryStatistics{count=2, sum=25, min=8, average=12.500000, max=17}
California: IntSummaryStatistics{count=3, sum=28, min=6, average=9.333333, max=12}
Utah: IntSummaryStatistics{count=2, sum=14, min=5, average=7.000000, max=9}
Nevada: IntSummaryStatistics{count=3, sum=14, min=4, average=4.666667, max=6}
How do you find the average of the max and min value in a String?
I also tried
replaceAll("[^0-9]", "").split("\\D+")
This is a good first step. It will give you an array of strings (String[]
). It is probably a good idea to then convert this to an int[]
. See Converting a String array into an int Array in java
Once you have an int[]
, you can calculate the max and the min by referring to Finding the max/min value in an array of primitives using Java
By the way, the average is not (1234/5678)/2. It is (1234 + 5678)/2
Related Topics
Java: Global Exception Handler
Parsing String to Local Date Doesn't Use Desired Century
Understanding the etc/Gmt Time Zone
Why Does Java Allow Arrays of Size 0
Why Does String.Replace Not Work
Java String.Split() Sometimes Giving Blank Strings
Differencebetween a += B and a =+ B , Also A++ and ++A
Alternative to Deprecated Getcelltype
How to Disable Loggers of a Class or of Whole Package
Differencebetween a Synchronized Method and Synchronized Block in Java
Displaying Am and Pm in Lower Case After Date Formatting
Include External Jar When Running Java -Jar
@Valid When Creating Objects with Jackson Without Controller
Make Simpledateformat.Parse() Fail on Invalid Dates (E.G. Month Is Greater Than 12)