Write a Java program using Lambda Expression to calculate the product of all even numbers in a list of integers
The java program that calculates the product of even 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 even and some are odd.
- System.out.println("Given Numbers : " + numbers); prints the original list of numbers.
- The program uses Java Streams to filter and calculate the product of even 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 even numbers in the stream by checking if each number is divisible by 2 (i.e., n % 2 == 0).
- .reduce(1, (a, b) -> a * b): This is a reduce operation that calculates the product of even numbers in the stream. It starts with an initial value of 1 and multiplies each even number with the accumulated product.
- System.out.println("Product of Even Numbers : " + product_even); prints the product of even numbers.
Source Code
import java.util.ArrayList;
import java.util.List;
public class ProductOfEvenNumber
{
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);
numbers.add(6);
System.out.println("Given Numbers : " + numbers);
int product_even = numbers.stream().filter(n -> n % 2 == 0).reduce(1, (a, b) -> a * b);
System.out.println("Product of Even Numbers : " + product_even);
}
}
Output
Given Numbers : [1, 2, 3, 4, 5, 6]
Product of Even Numbers : 48