Created
September 24, 2025 03:12
-
-
Save gigamonkey/2eb3b5394805ddb6cf983ce3fd9000af to your computer and use it in GitHub Desktop.
kicking the tires on Gatherer mechanism in Java streams.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.util.stream.*; | |
public class PrimeStream { | |
private static Gatherer<Long, List<Long>, Long> sieve = | |
Gatherer.ofSequential( | |
ArrayList::new, | |
(soFar, n, downstream) -> { | |
if (isPrime(soFar, n)) { | |
soFar.add(n); | |
downstream.push(n); | |
} | |
return true; | |
}); | |
// Assumes soFar has all the primes less than n and that n >= 2 | |
private static boolean isPrime(List<Long> soFar, long n) { | |
if (n == 2) return true; | |
for (long p : soFar) { | |
if (n % p == 0) return false; | |
if (p * p > n) break; | |
} | |
return true; | |
} | |
public static Stream<Long> primes() { | |
return Stream.iterate(2L, n -> n + 1).gather(sieve); | |
} | |
public static void main(String[] args) { | |
int nth = Integer.parseInt(args[0]) - 1; | |
System.out.println(primes().skip(nth).findFirst().get()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment