Write a Java program using Lambda Expression to find the average of a list of doubles
The java program that calculates the average of a list of Double values using Java Streams. Here's an explanation of the code:
- import java.util.Arrays;: This line imports the Arrays class from the java.util package, which is used to create a list of Double values from an array.
- import java.util.List;: This line imports the List class from the java.util package, which is used to work with lists.
- The Average class is defined, which contains the main method, where the program's execution begins.
- Inside the main method:
- List<Double> num = Arrays.asList(1.1, 2.2, 3.3, 4.4, 5.5);: This line creates a list of Double values named num containing the values 1.1, 2.2, 3.3, 4.4, and 5.5.
- double sum = num.stream().mapToDouble(Double::doubleValue).sum();: This line uses a stream to map each Double value to a primitive double using the mapToDouble operation and the Double::doubleValue method reference. Then, it calculates the sum of the double values using the sum operation, storing the result in the sum variable.
- double ave = sum / num.size();: This line calculates the average by dividing the sum by the number of elements in the num list and stores the result in the ave variable.
- System.out.println("Average : " + ave);: This line prints the calculated average.
Source Code
import java.util.Arrays;
import java.util.List;
public class Average
{
public static void main(String[] args)
{
List<Double> num = Arrays.asList(1.1, 2.2, 3.3, 4.4, 5.5);
double sum = num.stream().mapToDouble(Double::doubleValue).sum();
double ave = sum / num.size();
System.out.println("Average : " + ave);
}
}
Output
Average : 3.3