OnJava8-Examples/concurrent/ParallelPrime.java

36 lines
1020 B
Java
Raw Normal View History

// concurrent/ParallelPrime.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2016-07-05 14:46:09 -06: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.
2016-07-05 14:46:09 -06:00
import java.util.*;
import java.util.stream.*;
import static java.util.stream.LongStream.*;
import java.io.*;
import java.nio.file.*;
import onjava.Timer;
2016-07-05 14:46:09 -06:00
public class ParallelPrime {
2016-07-05 14:46:09 -06:00
static final int COUNT = 100_000;
public static boolean isPrime(long n) {
return rangeClosed(2, (long)Math.sqrt(n))
.noneMatch(i -> n % i == 0);
}
public static void main(String[] args)
throws IOException {
Timer timer = new Timer();
2016-07-05 14:46:09 -06:00
List<String> primes =
iterate(2, i -> i + 1)
.parallel() // [1]
.filter(ParallelPrime::isPrime)
2016-07-05 14:46:09 -06:00
.limit(COUNT)
.mapToObj(Long::toString)
.collect(Collectors.toList());
System.out.println(timer.duration());
2016-07-05 14:46:09 -06:00
Files.write(Paths.get("primes.txt"), primes,
StandardOpenOption.CREATE);
}
}
/* Output:
1197
*/