Skip to content

Instantly share code, notes, and snippets.

@Karunamon
Created January 13, 2015 00:46
Show Gist options
  • Save Karunamon/abc6483ac1d08f6cc137 to your computer and use it in GitHub Desktop.
Save Karunamon/abc6483ac1d08f6cc137 to your computer and use it in GitHub Desktop.
Stream vs for loop processing
import java.util.ArrayList;
class main {
public static void print(String arg) {
System.out.println(arg);
}
public static ArrayList<Boolean> worklist = new ArrayList<Boolean>();
public static void main(String[] args) {
Long time = System.nanoTime();
print("Generating articles");
// String name = "RandomString";
for (int i = 0; i < 100_000_000; i++) {
//String name = "RandomString" + i;
worklist.add(true);
}
worklist.add(false);
Long finalTime = System.nanoTime() - time;
System.out.println("Nanoseconds taken to generate articles: " + finalTime.toString());
//Grab things from the array via a for loop
System.out.println("For loop:");
time = System.nanoTime();
for (int i = 0; i < worklist.size(); i++) {
if (worklist.get(i) == false) {
print(worklist.get(i).toString());
break;
}
}
finalTime = System.nanoTime() - time;
print(finalTime.toString());
print("Stream process:");
time = System.nanoTime();
print(worklist.stream().filter(a -> a == false).findFirst().get().toString());
finalTime = System.nanoTime() - time;
System.out.println(finalTime);
}
}
//Generating articles
//Nanoseconds taken to generate articles: 1107403917
//For loop:
//false
//107945510
//Stream process:
//false
//418558240
//For extra fun, change the "stream" on line 36 to "parallelStream".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment