Write a Java program using Lambda Expression to find the product of all odd numbers in a list of integers


The java program that calculates the product 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 product 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 each number is not divisible by 2 (i.e., n % 2 != 0).
    • .reduce(1, (x, y) -> x * y): This is a reduce operation that calculates the product of the filtered odd numbers in the stream. It starts with an initial value of 1 and multiplies each odd number with the accumulated product using the lambda expression (x, y) -> x * y.
  • System.out.println("Product of Odd Numbers : " + product_odds); prints the product of odd numbers.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class ProductOfOddNumbers
{
	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);
		numbers.add(7);
 
		System.out.println("Given Numbers : " + numbers);
 
		int product_odds = numbers.stream().filter(n -> n % 2 != 0).reduce(1, (x, y) -> x * y);
 
		System.out.println("Product of Odd Numbers : " + product_odds);
	}
}

Output

Given Numbers : [1, 2, 3, 4, 5, 6, 7]
Product of Odd Numbers : 105

Example Programs