Write a Java program using Lambda Expression to find the sum of squares of even numbers in a list of integers


The java program that calculates the sum of the squares 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 sum of the squares 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).
    • .map(n -> n * n): This is a map operation that squares each even number in the stream using the lambda expression n -> n * n.
    • .reduce(0, Integer::sum): This is a reduce operation that calculates the sum of the squared even numbers in the stream. It starts with an initial value of 0 and adds each squared even number to the accumulated sum using Integer::sum.
  • System.out.println("Sum of Squares of Even Numbers : " + sum_squares); prints the sum of the squares of even numbers.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class SumOfSquaresOfEvenNumbers
{
	public static void main(String[] args)
	{
		List<Integer> numbers = new ArrayList<>();
		numbers.add(1);
		numbers.add(2);//4
		numbers.add(3);
		numbers.add(4);//16
		numbers.add(5);
		numbers.add(6);//36
		numbers.add(7);
		numbers.add(8);//64
		numbers.add(9);
		numbers.add(10);//100
 
		System.out.println("Given Numbers : " + numbers);
 
		int sum_squares = numbers.stream().filter(n -> n % 2 == 0).map(n -> n * n).reduce(0, Integer::sum);
 
		System.out.println("Sum of Squares of Even Numbers : " + sum_squares);
	}
}

Output

Given Numbers : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sum of Squares of Even Numbers : 220

Example Programs