2

for loop and foreach can use break instruction. but Java8 Consumer.

beans.forEach(v->{
    if (v.id != 100){
        //break or continue
    }
    v.doSomeThing();
});
assylias
  • 321,522
  • 82
  • 660
  • 783
gordonpro
  • 271
  • 3
  • 7
  • There is no simple way to do it - you could filter the elements or limit the number of elements but you can't easily break the forEach on a random condition. – assylias Apr 22 '14 at 08:30
  • 1
    You are using the wrong tools for the wrong job here, if you need such a condition, then just go with the regular for-loop, especially when you are not working with streams. – skiwi Apr 22 '14 at 08:39
  • @Holame A `continue` within a `forEach` is basically just filtering on the negation, so you could do something like `beans.stream().filter(v -> v.id == 100).forEach(v -> v.doSomeThing())`. – Stuart Marks Apr 23 '14 at 01:29
  • @StuartMarks indeed - you can close the question as a duplicate of that other question and both links will appear in the close reason. – assylias Apr 23 '14 at 01:31

2 Answers2

1

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
Nick Holt
  • 33,455
  • 4
  • 52
  • 58
0

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.

blalasaadri
  • 5,990
  • 5
  • 38
  • 58