Skip to content

Instantly share code, notes, and snippets.

@exoego
Created August 9, 2014 23:36
Show Gist options
  • Save exoego/e0967936955ab931c5ea to your computer and use it in GitHub Desktop.
Save exoego/e0967936955ab931c5ea to your computer and use it in GitHub Desktop.
findFirstなどStreamの途中で終了する末端処理が実行されると、中間処理(filter、mapなど)も途中で終了する。
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class FilterDoesNotConsumeWholeStream {
public static void main(String... args) {
final OptionalInt first = IntStream.range(1, 10).map(i -> {
if (i > 5) {
throw new IllegalStateException();
}
return i;
})
.filter(i -> i >= 4)
// 最初にi>=4となる要素が見つかった時点でStreamの消費が終了するので、例外が発生しない
.findFirst();
System.out.println(first);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment