×

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 Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.