for loop and foreach can use break instruction. but Java8 Consumer.
beans.forEach(v->{
if (v.id != 100){
//break or continue
}
v.doSomeThing();
});
for loop and foreach can use break instruction. but Java8 Consumer.
beans.forEach(v->{
if (v.id != 100){
//break or continue
}
v.doSomeThing();
});
It would have been nice to get away from helper methods in Java 8, but if you really need to break in a loop (filtering or setting a limit as @assylias suggests, is the way to avoid this) then just write a helper method:
public static <T> void forEach(Iterable<T> iterable, Function<T, Boolean> f)
{
for (T item : iterable)
{
if (!f.apply(item))
{
break;
}
}
}
This helper method can then be used like this:
List<Integer> integers = Arrays.asList(1, 2, 3, 4);
forEach(
integers,
(i) -> {
System.out.println(i);
return i < 2;
}
);
Which prints:
1
2
With Streams each element should be viewed independently or with as little knowledge as possible of the other items in the Stream; this is in part because of the possibility of using parallel Streams. A quote from the Stream JavaDoc:
Stream pipelines may execute either sequentially or in parallel. This execution mode is a property of the stream. Streams are created with an initial choice of sequential or parallel execution. (For example, Collection#stream() creates a sequential stream, and Collection#parallelStream() creates a parallel one.) This choice of execution mode may be modified by the Stream#sequential() or Stream#parallel() methods, and may be queried with the Stream#isParallel() method.
So, using break
in a parallel Stream could have unforeseen consequences.
The best idea is probably using a traditional for
-loop if you want to be able to break
or to filter the stream so as to not require a break
. Or maybe you have to rethink your logic entirely as Streams offer quite a few new possibilities.