Write a Java program using Lambda Expression to find the square root of each number in a list of doubles


The java program that calculates the square root of each number in a list of doubles and prints the results. Here's an explanation of the code:

  • An ArrayList named numbers is created to store a list of double values.
  • The program uses a lambda expression and the forEach method to iterate through the numbers list and calculate the square root for each number:
    • numbers.forEach((number) -> { ... }: This loop iterates through each element in the numbers list.
    • double square_root = Math.sqrt(number);: Inside the loop, it calculates the square root of the current number using the Math.sqrt function.
    • System.out.println("Square root of " + number + " is " + square_root);: It then prints the original number and its calculated square root.
  • As a result, the program calculates and prints the square root for each number in the list.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class SquareRoot
{
	public static void main(String[] args)
	{
		List<Double> numbers = new ArrayList<>();
		numbers.add(16.0);
		numbers.add(5.0);
		numbers.add(25.0);
		numbers.add(9.0);
		numbers.add(36.0);
 
		// Using Lambda Expression to calculate square root for each number
		numbers.forEach((number) -> {
			double square_root = Math.sqrt(number);
			System.out.println("Square root of " + number + " is " + square_root);
		});
	}
}

Output

Square root of 16.0 is 4.0
Square root of 5.0 is 2.23606797749979
Square root of 25.0 is 5.0
Square root of 9.0 is 3.0
Square root of 36.0 is 6.0

Example Programs