Write a Java program using Lambda Expression to calculate the sum of all Odd numbers


The java program that calculates the sum of odd numbers in a list of integers using Java Streams. Here's an explanation of the code:

  • import java.util.Arrays;: This line imports the Arrays class from the java.util package, which is used to create a list of integers from an array.
  • import java.util.List;: This line imports the List class from the java.util package, which is used to work with lists.
  • The SumOddNumber class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);: This line creates a list of integers named numbers containing the values from 1 to 10.
    • int odd_sum = numbers.stream().filter(num -> num % 2 == 1).mapToInt(Integer::intValue).sum();: This line uses a stream to filter odd numbers from the numbers list using the filter operation and the lambda expression num -> num % 2 == 1. Then, it uses the mapToInt operation to convert the filtered numbers to primitive int values, and finally, it calculates the sum of these int values using the sum operation. The result is stored in the odd_sum variable.
    • System.out.println("Sum of Odd Numbers : " + odd_sum);: This line prints the sum of odd numbers.

Source Code

import java.util.Arrays;
import java.util.List;
 
public class SumOddNumber
{
	public static void main(String[] args)
	{
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
		int odd_sum = numbers.stream().filter(num -> num % 2 == 1).mapToInt(Integer::intValue).sum(); 
		System.out.println("Sum of Odd Numbers : " + odd_sum);
	}
}

Output

Sum of Odd Numbers : 25

Example Programs