Skip to content

Instantly share code, notes, and snippets.

@ansig
Created August 1, 2016 12:45
Show Gist options
  • Save ansig/64c2b1987b7a8321bd22aad312a48e20 to your computer and use it in GitHub Desktop.
Save ansig/64c2b1987b7a8321bd22aad312a48e20 to your computer and use it in GitHub Desktop.
Demonstrates the time difference between sequential streams and parallel streams.
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