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.
See if this is it https://stackoverflow.com/questions/23308193/break-or-return-from-java-8-stream-foreach
– Diego Schmidt
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 onebreak
is wrong, although it works:https://i.stack.Imgur.com/Cqixb.jpg– Maniero
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 thefor
normal. It can’t be more efficient than that. Alias if efficiency is important this should be done even if you don’t need thebreak
. All this is in my answer.– Maniero