Languages
[Edit]
EN

Java - calculate average of ArrayList

0 points
Created by:
Kourtney-White
635

In this article, we would like to show you how to calculate the average of an ArrayList in Java.

Quick solution:

 

1. Using enhanced for loop

Edit

In this example, we calculate the average of myArrayList.

To do so we take the following steps:

  • create an Integer variable to sum all the ArrayList elements,
  • use Integer.doubleValue() method to convert the number to a double,
  • divide the sum of all elements by the  ArrayList size.

Output:

2. Using Streams

Edit

In this example, we use streams to calculate the average value of myArrayList.

Note:

This solution works only for Java 8 and newer versions.

Output:

References

Edit
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - ArrayList

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join