Write a Java program using Lambda Expression to calculate the sum of all prime numbers in a list of integers


The java program that calculates the sum of prime 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 prime and some are not.
  • System.out.println("Given Numbers : " + numbers); prints the original list of numbers.
  • The program uses Java Streams to filter and calculate the sum of prime numbers:
    • numbers.stream(): This converts the numbers list into a stream of integers.
    • .filter(SumOfPrimes::isPrime): This is a filter operation that retains only the prime numbers in the stream. The isPrime method is used as the filtering condition, and it checks if each number is prime or not.
    • .mapToInt(Integer::intValue): This is a map operation that converts the stream of filtered prime numbers into a stream of primitive integers.
    • .sum(): This calculates the sum of the prime numbers in the stream.
  • System.out.println("Sum of Prime Numbers : " + sum_primes); prints the sum of prime numbers.
  • The isPrime method is defined to check if a given number is prime or not. It iterates through numbers from 2 to the square root of the number, checking for divisibility. If the number is divisible by any number within this range, it is not prime.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class SumOfPrimes
{
	public static void main(String[] args)
	{
		List<Integer> numbers = new ArrayList<>();
		numbers.add(2);
		numbers.add(3);
		numbers.add(4);
		numbers.add(5);
		numbers.add(7);
		numbers.add(8);
 
		System.out.println("Given Numbers : " + numbers);
 
		int sum_primes = numbers.stream().filter(SumOfPrimes::isPrime).mapToInt(Integer::intValue).sum();
 
		System.out.println("Sum of Prime Numbers : " + sum_primes);
	}
 
	public static boolean isPrime(int number)
	{
		if (number <= 1) return false;
		for (int i = 2; i <= Math.sqrt(number); i++)
		{
			if (number % i == 0) return false;
		}
		return true;
	}
}

Output

Given Numbers : [2, 3, 4, 5, 7, 8]
Sum of Prime Numbers : 17

Example Programs