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


The Java program calculates the sum of the squares 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.
  • System.out.println("Given Numbers : " + numbers); prints the original list of numbers.
  • The program uses Java Streams to calculate the sum of squares of odd numbers:
    • numbers.stream(): This converts the numbers list into a stream of integers.
    • .filter(number -> number % 2 != 0): This filters the stream to keep only the odd numbers. The % operator is used to check if a number is odd (i.e., not divisible by 2).
    • .mapToInt(number -> number * number): This maps each odd number to its square (number * number). The mapToInt method is used to convert the stream of integers into a stream of primitive int.
    • .sum(): This calculates the sum of the squared odd numbers.
  • The program stores the result in the sum variable.
  • It then uses System.out.println("Sum of squares of odd Numbers : " + sum); to print the sum of the squares of odd numbers.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class SumOfSquaresOfOddNumbers
{
	public static void main(String[] args)
	{
		List<Integer> numbers = new ArrayList<>();
		numbers.add(1);//1
		numbers.add(2);
		numbers.add(3);//9
		numbers.add(4);
		numbers.add(5);//25
		numbers.add(6);
 
		System.out.println("Given Numbers : " + numbers);
 
		// Using Lambda Expression to find the sum of squares of odd numbers
		int sum = numbers.stream()
			.filter(number -> number % 2 != 0) // Filter out odd numbers
			.mapToInt(number -> number * number) // Square each odd number
			.sum(); // Calculate the sum
 
		System.out.println("Sum of squares of odd Numbers : " + sum);
	}
}

Output

Given Numbers : [1, 2, 3, 4, 5, 6]
Sum of squares of odd Numbers : 35

Example Programs