Assume a list of integers:
List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 10);
Approach: Using filter()
with a Prime Check
List<Integer> primes = numbers.stream() .filter(n -> n > 1 && IntStream.rangeClosed(2, (int)Math.sqrt(n)) .allMatch(i -> n % i != 0)) .collect(Collectors.toList()); System.out.println(primes);
Output:
[2, 3, 5, 7]
Summary:
- Use
IntStream.rangeClosed(2, sqrt(n))
to check divisibility. .filter()
retains only prime numbers..collect(Collectors.toList())
returns a list of primes.
This approach works efficiently for small to moderate-sized lists of integers.