Write a Java program using Lambda Expression to find the difference between the maximum and minimum values in a list of doubles


The java program that calculates the maximum and minimum values in a list of doubles and then calculates the difference between the maximum and minimum values. Here's an explanation of the code:

  • An ArrayList named numbers is created to store a list of double values.
  • The numbers list is populated with double values.
  • System.out.println("Given Numbers : " + numbers); prints the original list of numbers.
  • The program uses Java Streams to calculate the maximum and minimum values:
    • numbers.stream().max(Double::compareTo).orElse(0.0): This stream operation calculates the maximum value in the list by comparing the elements using the Double::compareTo method. If there are no elements, it returns a default value of 0.0 using orElse.
    • numbers.stream().min(Double::compareTo).orElse(0.0): This stream operation calculates the minimum value in the list using the same approach.
  • The difference between the maximum and minimum values is calculated by subtracting the minimum from the maximum.
  • System.out.println("Maximum : " + max); prints the maximum value.
  • System.out.println("Minimum : " + min); prints the minimum value.
  • System.out.println("Difference between Maximum and Minimum : " + difference); prints the difference between the maximum and minimum values.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class MaxMinDifference
{
	public static void main(String[] args)
	{
		List<Double> numbers = new ArrayList<>();
		numbers.add(10.5);
		numbers.add(5.2);
		numbers.add(8.7);
		numbers.add(15.1);
		numbers.add(3.3);
 
		System.out.println("Given Numbers : " + numbers);
 
		double max = numbers.stream().max(Double::compareTo).orElse(0.0);
 
		double min = numbers.stream().min(Double::compareTo).orElse(0.0);
 
		double difference = max - min;
 
		System.out.println("Maximum : " + max);
		System.out.println("Mininum : " + min);		
		System.out.println("Difference between Maximum and Mininum : " + difference);
	}
}

Output

Given Numbers : [10.5, 5.2, 8.7, 15.1, 3.3]
Maximum : 15.1
Mininum : 3.3
Difference between Maximum and Mininum : 11.8

Example Programs