Write a Java program using Lambda Expression that takes a list of numbers and returns the square of each number
The java program that demonstrates the use of lambda expressions to square each number in a list. Here's an explanation of the code:
- import java.util.ArrayList;: This line imports the ArrayList class from the java.util package, which is used to create an ArrayList to store integers.
- import java.util.List;: This line imports the List interface from the java.util package, which is used to work with lists.
- The Main class is defined, which contains the main method and another method named squareNumbers.
- Inside the main method:
- List<Integer> numbers = new ArrayList<>();: This line creates an ArrayList named numbers to store integers.
- numbers.add(1);, numbers.add(2);, numbers.add(3);, numbers.add(4);, and numbers.add(5);: These lines add integers (1, 2, 3, 4, and 5) to the numbers list.
- List squarednumbers = squareNumbers(numbers);: This line calls the squareNumbers method, passing the numbers list as an argument. It receives a new list of squared numbers in return.
- System.out.println("Given Numbers : " + numbers); : This line prints the original list of numbers.
- System.out.println("Squared Numbers : " + squarednumbers);: This line prints the list of squared numbers.
- The squareNumbers method is defined with the following functionality:
Source Code
import java.util.ArrayList;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Define the lambda expression to square each number
List<Integer> squarednumbers = squareNumbers(numbers);
// Print the squared numbers
System.out.println("Given Numbers : " + numbers);
System.out.println("Squared Numbers : " + squarednumbers);
}
public static List<Integer> squareNumbers(List<Integer> numbers)
{
// Use lambda expression to square each number
List<Integer> squarednumbers = new ArrayList<>();
numbers.forEach(number -> squarednumbers.add(number * number));
return squarednumbers;
}
}
Output
Given Numbers : [1, 2, 3, 4, 5]
Squared Numbers : [1, 4, 9, 16, 25]