Created
April 25, 2022 12:00
-
-
Save wcang/6a81704eaa9bc4b54d686a313a9dae97 to your computer and use it in GitHub Desktop.
PrimeNumberCollector that collects prime numbers into a list from an Integer stream. OptimizedPrimeNumberCollector is an optimized version of the collector using the accumulated list of prior prime numbers to weed out a prime number candidate. Refers to Java 8 In Action for details
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
| package com.wcang; | |
| import java.time.Duration; | |
| import java.time.Instant; | |
| import java.util.List; | |
| import java.util.function.Function; | |
| import java.util.stream.Collectors; | |
| import java.util.stream.IntStream; | |
| public class Main { | |
| public static void main(String[] args) { | |
| Instant start, stop; | |
| start = Instant.now(); | |
| List<Integer> primes = (IntStream.rangeClosed(0, 10000000)).parallel().boxed().filter(PrimeNumberCollector::isPrime).collect(Collectors.toList()); | |
| stop = Instant.now(); | |
| long timeElapsed = Duration.between(start, stop).toMillis(); | |
| System.out.println(primes); | |
| start = Instant.now(); | |
| List<Integer> optimizedPrimes = IntStream.rangeClosed(0, 10000000).boxed().collect(new OptimizedPrimeNumberCollector()); | |
| stop = Instant.now(); | |
| long timeOptimizedElapsed = Duration.between(start, stop).toMillis(); | |
| System.out.println(optimizedPrimes); | |
| System.out.printf("Optimized and unoptimized prime numbers %s\n", primes.equals(optimizedPrimes) ? "matches" : "doesn't match"); | |
| System.out.printf("Optimized elapsed time %d ms unoptimized elapsed time %d ms\n", timeOptimizedElapsed, timeElapsed); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment