Write a Java program using Lambda Expression to find the sum of squares of all numbers from 1 to 10


The java program that calculates the sum of the squares of all numbers from 1 to 10 using the IntStream class from the Java Stream API. Here's an explanation of the code:

  • The program uses the IntStream.rangeClosed(1, 10) method, which creates an IntStream that represents a range of integers from 1 to 10, inclusive.
  • .map(n -> n * n): This is a mapping operation that squares each number in the stream using the lambda expression n -> n * n.
  • .sum(): This calculates the sum of the squared numbers in the stream.
  • System.out.println("Sum of Squares of all numbers from 1 to 10 : " + sum_squares); prints the sum of the squares of the numbers in the specified range.

Source Code

import java.util.stream.IntStream;
 
public class SumOfSquareNumber
{
	public static void main(String[] args)
	{
		int sum_squares = IntStream.rangeClosed(1, 10).map(n -> n * n).sum();
 
		System.out.println("Sum of Squares of all numbers from 1 to 10 : " + sum_squares);
	}
}

Output

Sum of Squares of all numbers from 1 to 10 : 385

Example Programs