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


The java program that calculates the sum of even 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 SumEvenNumber class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • List<Integer> 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 even_sum = numbers.stream().filter(num -> num % 2 == 0).mapToInt(Integer::intValue).sum();: This line uses a stream to filter even numbers from the numbers list using the filter operation and the lambda expression num -> num % 2 == 0. 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 even_sum variable.
    • System.out.println("Sum of Even Numbers : " + even_sum);: This line prints the sum of even numbers.

Source Code

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

Output

Sum of Even Numbers : 30

Example Programs