javalistjava-streamprimes

Get prime numbers from a List using a Java stream


How can I filter to get prime numbers from a list?

I am wondering if that possible to check using only one long return and streams.

public static List<Integer> primeNumbers(List <Integer> list) {
    return Optional.ofNullable(list)
             .orElse(Collections.emptyList())
             .stream()
             .filter(Objects::nonNull)
             .filter(i -> i %2 ==0)
             .toList();
}

Solution

  • You could use (or misuse) BigInteger.isProbablePrime:

    import java.math.BigInteger;
    ....
    
    public static List<Integer> primeNumbers(List <Integer> list) {
        return list.stream()
                   .filter(i -> BigInteger.valueOf(i).isProbablePrime(10))
                   .collect(Collectors.toList());
    }