Java Program to Find Average of Two Lists
Last Updated :
13 Dec, 2023
To calculate the average of two lists in Java we first need to combine the two lists into one. we can do this using the addAll() method of the ArrayList class. Once you have combined the lists we can calculate the average by summing up all the elements in the combined list and dividing by the total number of factors.
Methods to Find Average of Two Lists
There are three methods to find the average of the two lists are mentioned below:
- Using simple for loop +len() and + Operator
- Using the sum(), len() and + Operators
- Using sum() + len() + chain()
1. Using simple for loop +len() and + Operator
Below is the Implementation of the above method:
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
list1.add( 1 );
list1.add( 2 );
list1.add( 3 );
list2.add( 4 );
list2.add( 5 );
list2.add( 6 );
double avg = 0 ;
for ( int i = 0 ; i < list1.size(); i++)
avg += list1.get(i);
for ( int i = 0 ; i < list2.size(); i++)
avg += list2.get(i);
int l = list1.size() + list2.size();
System.out.println( "Average: " + avg / l);
}
}
|
2. Using the sum(), len(), and + operators
Below is the Implementation of the above method:
Java
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args)
{
List<Integer> list1
= new ArrayList<>(Arrays.asList( 1 , 2 , 3 ));
List<Integer> list2
= new ArrayList<>(Arrays.asList( 4 , 5 , 6 ));
double average = (( double )list1.stream()
.mapToInt(Integer::intValue).sum()
+ ( double )list2.stream()
.mapToInt(Integer::intValue).sum())
/ (list1.size() + list2.size());
System.out.println( "Average: " + average);
}
}
|
3. Using sum() + len() + chain()
Below is the Implementation of the above method:
Java
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class AverageOfTwoLists {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList( 1 , 2 , 3 , 4 , 5 );
List<Integer> list2 = Arrays.asList( 6 , 7 , 8 , 9 , 10 );
double average = Stream.concat(list1.stream(), list2.stream())
.mapToInt(Integer::intValue)
.average()
.orElse(Double.NaN);
System.out.println( "Average: " + average);
}
}
|
Share your thoughts in the comments
Please Login to comment...