Skip to content

Instantly share code, notes, and snippets.

@george-hawkins
Created August 27, 2016 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save george-hawkins/17e904078e76d5d9c8c0dcc54ab09af6 to your computer and use it in GitHub Desktop.
Save george-hawkins/17e904078e76d5d9c8c0dcc54ab09af6 to your computer and use it in GitHub Desktop.
Do streams involve upfront calculation in Java?
package net.betaengine;
import java.util.stream.IntStream;
public class StreamCost {
private boolean isPrime(int n) {
System.out.println("Checking if " + n + " is a prime.");
return IntStream.range(2, n).allMatch(x -> n % x != 0);
}
private void run() {
IntStream stream = IntStream.range(1000, 10001).filter(this::isPrime);
System.out.println("Finding second prime...");
stream.skip(1).findFirst().ifPresent(n -> System.out.println("Second prime: " + n));
}
public static void main(String[] args) {
new StreamCost().run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment