Break and Continue on foreach Java 8

Asked

Viewed 4,293 times

5

How to give a break or a continue in an iteration using forEach, in the example below, I could use the same forEach for the execution of the validation?

List<Contratos> contratos= /* populando contratos*/;
contratos.forEach(numero ->{

    if( /* condicao de salvamento*/){
       /* Adiciona a lista para salvar*/
    }
    if(/* condicao de validação*/ ){
        break;
    }
});
  • See if this is it https://stackoverflow.com/questions/23308193/break-or-return-from-java-8-stream-foreach

  • 1

    You can’t change the question. You asked how to give a break, then I answered that there is no way to give, then you changed the question saying that you know that there is no way to give, but if the initial question was how to give was with my answer that learned that there is no way to give, so my answer answered your question and then you wanted to ask another question. Even the new one, I still answered what you can do and what you shouldn’t do and obviously I won’t show you what you shouldn’t do. Qq solution q be use this method if you need one break is wrong, although it works:https://i.stack.Imgur.com/Cqixb.jpg

  • 1

    And even in the new question I answered too: Sei que não existe o break no forEach, gostaria de saber qual seria a forma mais eficiente de codificar isso?My answer was not to use this method and to use the for normal. It can’t be more efficient than that. Alias if efficiency is important this should be done even if you don’t need the break. All this is in my answer.

2 answers

7


There is no break and continue stream, as your primary goal is to run iterations in parallel, so giving a "break" or a "continue" would be extremely inefficient and would most likely result in wrong returns, After all he could not communicate the threads in parallel and at different times that should "continue" or "stop" the execution. In the given example what could be done would be a filter to remove the unwanted number, and later run the foreach running what should be run, but with the unwanted item already removed from the list.

numeros.stream().filter( e -> e!= 4).forEach(numero ->{/*seu codigo*/ } );

As it is not possible to do this using the foreach an elegant solution without replacing the lambda would be using the throw Exception:

List<Contratos> contratos= /* populando contratos*/;
try {
    contratos.forEach(numero ->{
        if( /* condicao de salvamento*/){
           /* Adiciona a lista para salvar*/
        }
        if(/* condicao de validação*/ ){
             throw new BreakException();
        }
    });
}catch (BreakException e) {
    // aqui vc saberia se foi dado o "break"
}

Or simply add the validation in the same if of the save, running the entire array, obviously losing efficiency

5

Well, for this example it doesn’t make much sense, but I will consider it to be used somewhere it does. And it depends on the concrete example to give a suitable solution. Anyway the forEach() It is almost always not the right solution, and if you need this flow control you are probably already missing before in choosing to use it, even more so in this example. If it’s easier to do with the for so that complicate and slow down the code?

In general the Continue is solved by changing the flow of the code, it is always possible to do this to avoid the continue, although in some cases the code gets worse. I could only speak in a concrete example.

The break is more complicated and the solution is not to do this, just to prevent the code from running completely, ie you exchange the break for continue (not literally, just changing the flow) and it doesn’t end before, just doesn’t perform anything else on each item, terrible solution, so do it the right way and don’t use this method.

There is the solution of the exception being launched, but it is the worst use of an exception I have ever seen in life.

Of course if you need to stop before you have other methods of Stream who can do what you wish.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.