Reputation: 339
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;
}
Upvotes: 1
Views: 3944
Reputation: 33476
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 (int) players.stream()
.filter(p -> p.level > average)
.count();
Upvotes: 6
Reputation: 2307
Your code works in O(n)
, since you travel through array twice. Well, since you have to calculate average, that means you have to travel at least once, so there is no option for performance faster then O(n)
.
Second thing you do, you must count players with level higher then average. Only speedup here could be if you have sorted array (have before, not calculating now, since its O(nlogn)
, then you can find first one with higher level then average and calculate number of the rest. That would cost O(logn)
, but its performance is still O(n)
, since you calculated average.
Upvotes: 2