Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Foreach with a condition

Tags:

java

foreach

Is it possible for Java foreach to have conditions?

For example,

for(Foo foo : foos && try == true) { //Do something } 

Is there an equivalent to this, such that I can put an AND condition inside for?

like image 771
TJ- Avatar asked Apr 11 '12 10:04

TJ-


People also ask

Can we put condition in forEach?

No, a foreach simply works for each element.

How do you call a method in forEach in Java 8?

If the purpose of forEach() is just iteration then you can directly call it like list. forEach() or set. forEach() but if you want to perform some operations like filter or map then it better first get the stream and then perform that operation and finally call forEach() method.

Does Break work in forEach Java?

You can't.

How does forEach works in Java?

The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.


2 Answers

No.

You could use a while loop instead.

Iterator iterator = list.iterator(); while(iterator.hasNext()) {     ... } 
like image 69
NimChimpsky Avatar answered Sep 21 '22 13:09

NimChimpsky


No, there is nothing like that. The "enhanced for loop" is a completely separate construct that does nothing except lopp through the iterator returned by its Iterable parameter.

What you can do is this:

for(Foo foo : foos) {    //Do something    if(!condition){        break;    } } 
like image 38
Michael Borgwardt Avatar answered Sep 17 '22 13:09

Michael Borgwardt