I\'m trying to use the below code to calculate the average of a set of values that a user enters and display it in a jTextArea but it does not work properly. Sa
If using Java8 you can get the average of the values from a List as follows:
List intList = Arrays.asList(1,2,2,3,1,5);
Double average = intList.stream().mapToInt(val -> val).average().orElse(0.0);
This has the advantage of having no moving parts. It can be easily adapted to work with a List of other types of object by changing the map method call.
For example with Doubles:
List dblList = Arrays.asList(1.1,2.1,2.2,3.1,1.5,5.3);
Double average = dblList.stream().mapToDouble(val -> val).average().orElse(0.0);
NB. mapToDouble is required because it returns a DoubleStream which has an average method, while using map does not.
or BigDecimals:
@Test
public void bigDecimalListAveragedCorrectly() {
List bdList = Arrays.asList(valueOf(1.1),valueOf(2.1),valueOf(2.2),valueOf(3.1),valueOf(1.5),valueOf(5.3));
Double average = bdList.stream().mapToDouble(BigDecimal::doubleValue).average().orElse(0.0);
assertEquals(2.55, average, 0.000001);
}
using orElse(0.0) removes problems with the Optional object returned from the average being 'not present'.