The challenge
Find the mean (average) of a list of numbers in an array.
To find the mean (average) of a set of numbers add all of the numbers together and divide by the number of values in the list.
For an example list of 1, 3, 5, 7
1. Add all of the numbers
2. Divide by the number of values in the list. In this example there are 4 numbers in the list.
3. The mean (or average) of this list is 4
Test cases
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import static org.junit.Assert.*;
import org.junit.Test;
public class AveragerTest {
@Test
public void test1() {
assertEquals(1,
Averager.findAverage(new int[]{1}));
}
@Test
public void test2() {
assertEquals(4,
Averager.findAverage(new int[]{1,3,5,7}));
}
}
|
Find the Mean/Average in Java
Avoid performing a for loop, in favour of an Arrays.stream
:
1
2
3
4
5
6
7
8
|
import java.util.*;
public class Averager {
public static int findAverage(int[] nums) {
// sum all the elements and divide by the amount of elements
return Arrays.stream(nums).sum()/nums.length;
}
}
|
Alternatively, use the average
functional directly and avoid summing and dividing by the length:
1
2
3
4
5
6
7
8
|
import java.util.Arrays;
public class Averager {
public static int findAverage(int[] nums) {
// or use the internal `average`
return (int)Arrays.stream(nums).average().orElse(0);
}
}
|
Another great option is to use the summaryStatistics
extension of the InStream
class to then in turn use the getAverage
method as follows:
1
2
3
4
5
6
7
8
|
import java.util.stream.IntStream;
public class Averager {
public static int findAverage(int[] nums) {
// or explore the `summaryStatistics` route
return (int)IntStream.of(nums).summaryStatistics().getAverage();
}
}
|
If all else fails, there’s always good old faithful, using a for loop:
1
2
3
4
5
6
7
8
9
|
public class Averager {
public static int findAverage(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum / nums.length;
}
}
|