rks rks - 6 months ago 9
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

ArrayList
.

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) {
bestPlayers++;
}
}

return bestPlayers;
}

Answer

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

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

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

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