Home > database >  get prime numbers from List using java stream
get prime numbers from List using java stream

Time:11-03

As mentioned in title of problem I wrote method like that. I don't know how to filter to get prime numbers from list. edit: i was wondering if that possible to check using only one long return and streams edit2: know i know i cannot

   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();
    }

Sorry for mistakes, first post here

CodePudding user response:

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());
}
  • Related