HomeLanguagesJavaJava Program to Find Average of Two Lists

Java Program to Find Average of Two Lists

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 two methods to find the average of the two lists are mentioned below:

  • Using the sum(), len() and + Operators
  • Using sum() + len() + chain()

1. Using the sum(), len(), and + operators

Below is the Implementation of the above method:

Java




// Java Program to Using the 
// sum(), len(), and + operators
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
  
// Driver Class
public class Main {
    // main function
    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);
    }
}


Output

Average: 3.5

2. Using sum() + len() + chain()

Below is the Implementation of the above method:

Java




// Java Program to demonstrate
// Using sum() + len() + chain()
import java.io.*;
import java.util.*;
import java.util.stream.*;
  
// Driver Class
public class AverageOfTwoLists {
      // main function
    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);
    }
}


Output

Average: 5.5

RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32686 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7052 POSTS0 COMMENTS
Nicole Veronica
12191 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12291 POSTS0 COMMENTS
Shaida Kate Naidoo
7177 POSTS0 COMMENTS
Ted Musemwa
7444 POSTS0 COMMENTS
Thapelo Manthata
7156 POSTS0 COMMENTS
Umr Jansen
7146 POSTS0 COMMENTS