Skip to content

Instantly share code, notes, and snippets.

@gtrefs
Created March 11, 2016 19:36
Show Gist options
  • Save gtrefs/355afbeaab05c806707e to your computer and use it in GitHub Desktop.
Save gtrefs/355afbeaab05c806707e to your computer and use it in GitHub Desktop.
Java 8 Primes
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
import org.junit.Test;
public class Primes {
final IntPredicate isPrime = x -> IntStream.rangeClosed(2, (int) (Math.sqrt(x))).allMatch(n -> x % n != 0);
final Function<Integer, IntStream> till = max -> IntStream.iterate(1, i -> i + 1).filter(isPrime).limit(max);
@Test
public void primesTill20() {
till.apply(20).forEach(prime -> System.out.println("Prime: " + prime));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment