rks rks - 1 year ago 51
Java Question

What's the best way to find the average value of objects stored in an arraylist?

I have a method that returns a count of the objects that have a higher value than the average of all the objects within an


The 'User' object has the integer value stored within it's class (level).

My method works but I'm wondering if there's a better way of finding the average of all object values?

public int bestPlayers() {

ArrayList<User> players = new ArrayList<User>();
int bestPlayers = 0;
int totalPlayerLevel = 0;
double averageLevel = 0;

for (int i = 0; i < players.size(); i++) {
totalPlayerLevel += players.get(i).level;

averageLevel = totalPlayerLevel / players.size();

for (int i = 0; i < players.size(); i++) {
if (players.get(i).level > averageLevel) {

return bestPlayers;

Answer Source

Java 8 provides a better way, using IntStream#average():

double average = players.stream()
                        .mapToInt(p -> p.level)

Then to output the number of "above average" players:

return players.stream()
              .filter(p -> p.level > average)