2

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

beans.forEach(v->{
    if (v.id != 100){
        //break or continue
    }
    v.doSomeThing();
});
4
  • 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. Commented Apr 22, 2014 at 8: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. Commented Apr 22, 2014 at 8: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()). Commented Apr 23, 2014 at 1:29
  • @StuartMarks indeed - you can close the question as a duplicate of that other question and both links will appear in the close reason. Commented Apr 23, 2014 at 1:31

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.