
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find average of a list in Java
Given a list of numbers, our task is to calculate the average of this list. The average of a list can be found by adding all the elements in the list and dividing the sum by the total number of elements. In this article we will learn different methods to implement this in Java.
There are multiple ways in Java to find the average of a list. In this article we will explore two different approaches:
Find Average of a List Using Java Streams
This approach shows how to find the average of a list of numbers using Stream API. First, the list is converted into streams, and then the average is found by using the getAverage() method of the IntSummaryStatistics class.
Example
The following code shows how to find average of a list using java streams:
import java.util.*; public class Demo { public static void main(String []args){ List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500); IntSummaryStatistics summaryStats = list.stream() .mapToInt((a) -> a) .summaryStatistics(); System.out.println("Average of a List = "+summaryStats.getAverage()); } }
Output
The above program produces the following result:
Average of a List = 156.66666666666666
Find Average of a List Using for Loop
In this approach, the average of the list is found by using a for loop. First we iterate through each element in the list using a for loop and add it to a variable called sum. And then the total sum is divided by the number of elements in the list, which is found using 'list.size()'.
Example
The following code shows the implementation of this approach in Java:
import java.util.*; public class Demo { public static void main(String []args){ List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500); int sum = 0; for (int i : list) { sum+=i; } if(list.isEmpty()){ System.out.println("Empty list!"); } else { System.out.println("Average = " + sum/(float)list.size()); } } }
Output
The above program produces the following result:
Average = 156.66667