31 lines
856 B
Java
Raw Normal View History

// streams/Prime.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
import java.util.stream.*;
import static java.util.stream.LongStream.*;
public class Prime {
public static boolean isPrime(long n) {
2015-11-15 15:51:35 -08:00
return rangeClosed(2, (long)Math.sqrt(n))
.noneMatch(i -> n % i == 0);
}
public LongStream numbers() {
return iterate(2, i -> i + 1).filter(Prime::isPrime);
}
public static void main(String[] args) {
new Prime().numbers()
2015-11-14 16:18:05 -08:00
.limit(10)
.forEach(n -> System.out.format("%d ", n));
System.out.println();
new Prime().numbers()
.skip(90)
.limit(10)
.forEach(n -> System.out.format("%d ", n));
}
}
2015-11-14 16:18:05 -08:00
/* Output:
2 3 5 7 11 13 17 19 23 29
467 479 487 491 499 503 509 521 523 541
*/