Skip to content
Advertisement

Prime number in java 8

I was trying to write a simple prime number program in Java 8. Below is the program. I wanted to reduce the code in isPrime() as well. Is there something that filters the elements from 2 to n/2, and then apply filter for n%i == 0 which would make isPrime irrelevant?

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Stream1 {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 20);
        // Prime number 
        System.out.println(numbers.stream()
                             .filter(Stream1::isPrime)
                             .collect(toList()));
    }

    public static boolean isPrime(int number) {
        for (int i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Advertisement

Answer

IntStream can be used to generate integer stream

public static boolean isPrime(int number) {
    return !IntStream.rangeClosed(2, number/2).anyMatch(i -> number%i == 0); 
}

or

public static boolean isPrime(int number) {
    return IntStream.rangeClosed(2, number/2).noneMatch(i -> number%i == 0);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement