Created
August 1, 2016 12:45
-
-
Save ansig/64c2b1987b7a8321bd22aad312a48e20 to your computer and use it in GitHub Desktop.
Demonstrates the time difference between sequential streams and parallel 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
public class Java8ParallelStream { | |
public static void main(String[] args) { | |
List<String> values = new ArrayList<>(); | |
int max = 1000000; | |
for (int i = 0; i < max; i++) { | |
UUID id = UUID.randomUUID(); | |
values.add(id.toString()); | |
} | |
NoArgsFunction sequential = () -> values.stream().sorted().count(); | |
NoArgsFunction parallel = () -> values.parallelStream().sorted().count(); | |
time(sequential); | |
time(parallel); | |
} | |
static void time(NoArgsFunction f) { | |
long t0 = System.nanoTime(); | |
f.execute(); | |
long t1 = System.nanoTime(); | |
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); | |
System.out.println(String.format("Took: %d ms", millis)); | |
} | |
@FunctionalInterface | |
private interface NoArgsFunction { | |
void execute(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment