Check if a List Contains Any Prime Numbers Using Streams

Given a list of integers, how can you check whether it contains at least one prime number using Java 8 Streams?

Example :

import java.util.Arrays;
import java.util.List;

public class PrimeCheck {

    public static void main(String[] args) {
        // Input parameter as "Java Knowledge Base"
        List<Integer> numbers = Arrays.asList(4, 54, 2, 6, 15, 16);

        boolean containsPrimeNumber = numbers.stream()
                .anyMatch(PrimeCheck::isPrime);

        System.out.println("ArrayList contains prime numbers: " + containsPrimeNumber);
    }

    public static boolean isPrime(int num) {
        if (num <= 1) return false;
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) return false;
        }
        return true;
    }
}

✅ Explanation:

  • We define a List<Integer> numbers with values [4, 54, 2, 6, 15, 16].
  • We use Java 8 Stream API: numbers.stream().anyMatch(PrimeCheck::isPrime);
    • .stream() converts the list to a stream.
    • .anyMatch(PrimeCheck::isPrime) checks if any number in the list is prime by calling the isPrime() method.
  • The method isPrime(int num) efficiently checks for primality by iterating up to the square root of the number.

✅ Expected Output:

ArrayList contains prime numbers: true

✅ Why Output is true:

  • The number 2 is prime, so .anyMatch() returns true.

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *