Write a Java program using Lambda Expression to find the square of each odd number in a list of integers
The java program that calculates the square of odd numbers from a list of integers using Java Streams. Here's an explanation of the code:
- An ArrayList named numbers is created to store a list of integers.
- The numbers list is populated with integers, some of which are odd and some are even.
- System.out.println("Given Numbers : " + numbers); prints the original list of numbers.
- The program uses Java Streams to filter and calculate the squares of odd numbers:
- numbers.stream(): This converts the numbers list into a stream of integers.
- .filter(n -> n % 2 != 0): This is a filter operation that retains only the odd numbers in the stream by checking if the remainder of each number when divided by 2 is not equal to 0.
- .map(n -> n * n): This is a map operation that squares each odd number in the stream using the lambda expression n -> n * n.
- .collect(Collectors.toList()): This collects the squared odd numbers into a new list named squaresOfOdds.
- System.out.println("Squares of Odd Numbers : " + squaresOfOdds); prints the list of squares of odd numbers.
Source Code
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class SquareOfOddNumbers
{
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);
System.out.println("Given Numbers : " + numbers);
List<Integer> squaresOfOdds = numbers.stream().filter(n -> n % 2 != 0).map(n -> n * n).collect(Collectors.toList());
System.out.println("Squares of Odd Numbers : " + squaresOfOdds);
}
}
Output
Given Numbers : [1, 2, 3, 4, 5]
Squares of Odd Numbers : [1, 9, 25]