×

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find the list's minimum and maximum elements, sum, and average. We will calculate the list's average using Java for loop, Java 8 Stream, and the class IntSummaryStatistics.

Using Loops

The reasoning is fairly basic. First, we'll set the value of a variable called sum, which stores the total of the list's members, to zero. Declare a further element called average, which contains the list's average.

To add the elements to the List, we built an instance of the ArrayList class and used its add () function. Every time the list is iterated over, a for loop retrieves an entry and adds it to the variable sum.

After that, we estimated the list's average by dividing the sum by the list's length.

Java Program to find the average of the list using loops

AverageOfList.java

import java . util . * ;     
public class AverageOfList1 
{  
public static void main ( String args [ ] )   
{  
int s1 = 0 , average=0 ;      
ArrayList <Integer> list1 = new ArrayList < Integer > () ;    
// Elements are added using add() method   
Scanner sc = new Scanner ( System . in ) ;
//System.out.println(" enter the elements of the list ");


list1 . add ( 42 ) ;  
list1 . add ( 31 ) ;  
list1 . add ( 50 ) ;  
list1 . add ( 418 ) ;  
list1 . add ( 265 ) ;  
System.out.println(" The elements of the list ");
for(int i=0;i< list1.size();i++)
{
    int r=list1.get(i);
    System.out.println(r);
}
// Iterating over the loop to get a sum of the elements of the list
for ( int j = 0 ; j < list1 . size ( ) ; j++ )  
s1 = s1 + list1 . get ( j ) ;  
average = s1 / list1 . size ( ) ;   
System . out . println ( " Average of the List: " + average ) ;  
}  
}  

Output

Java Calculate Average of List

Java Program to find the average of the list using each loop

import java . util . * ;  
public class Main  
{  
public static void main ( String s [ ] )  
{  
List < Integer > list1 = Arrays . asList ( 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 , 100 ) ;  
// integer variable declaration to store the sum of elements of the list 
int sum1 = 0;  
// using each loop to iterate through the list and to get the sum value 
for (int j : list)   
{  
sum1 += j;  
}  
// checking  if the list is empty  
if( list1 . isEmpty ( ) )  
{  
System . out . println ( " Empty List  " ) ;  
}   
else   
{  
System.out.println("The average of the List is: " + sum1/(float)list1.size());  
}  
}  
}  

Output:

Java Calculate Average of List

Implementing the IntSummaryStatistics Class

The class IntSummaryStatistics is part of java.util package. It uses IntStream class implementation. The focus of the class is using streams. An object of the state is used to gather statistics like count, min, max, total, and average.

stream()

This collection serves as the source of the sequential Stream returned by the function

mapToInt()

It is a lazy intermediate operation. Once the operations have completed their processing, they return a Stream instance as their output. The operations are called on a Stream instance.

summaryStatistics()

 This function produces an IntSummaryStatistics containing different summary information about the stream's elements, such as the total number of elements, the stream's average value, the minimum and maximum elements, and more. This is the last action. It implies that it might cross the stream to arrive at a conclusion.

getAverage()

 This method provides the arithmetic mean of the values that have been recorded, or 0 if no values have been recorded.

Main.java

import java . util . * ;  
public class Main  
{  
public static void main ( String s [] )  
{  
List<Integer> list1 = Arrays . asList ( 23 , 516 , 278 , 32 , 6 , 89  , 121 , 534 , 234 , 1 , 5 ) ;  
IntSummaryStatistics r = list1 . stream ( ) . mapToInt( ( a ) -> a ) . summaryStatistics ( ) ;  
System . out . println ( " The average of the List is: "+ r . getAverage ( ) ) ;  
}  
}  

Output

Java Calculate Average of List

Related Topics

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.