Home > Net >  How to simply conduct statistical operations across the elements of an ArrayList<>
How to simply conduct statistical operations across the elements of an ArrayList<>

Time:10-27

Suppose I have the following ArrayList<>:

ArrayList<Person> persons = new ArrayList<>();

The class Person looks like this:

public class Person {

String name;
int heightInCm;
int weightInKg;

// the class has the usual constructor, getters and setters

}

There are a variable number of instances of Person in persons (meaning persons.size() is not fixed).

Is there a simple way (i.e. using class library tools) to calculate for e.g. heightInCm the average value in persons, or determine the maximum value, or the minimum value, or ... ?

I could write some rather extensive code (using multiple loops etc.) to do the job, but surely there must be a built-in way. Thanks in advance.

CodePudding user response:

You can use the stream API with the summarizingInt collector.

It will return a IntSummaryStatistics object, containing the count, sum, min, max and average.

Example:

ArrayList<Person> persons = new ArrayList<>();
IntSummaryStatistics stat = persons.stream()
                                   .collect(Collectors.summarizingInt(Person::getHeightInCm));
  • Related