Created
August 9, 2014 23:36
-
-
Save exoego/e0967936955ab931c5ea to your computer and use it in GitHub Desktop.
findFirstなどStreamの途中で終了する末端処理が実行されると、中間処理(filter、mapなど)も途中で終了する。
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
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