31

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?

TJ-
  • 14,085
  • 12
  • 59
  • 90
  • For more information you may take a look at http://stackoverflow.com/a/3433775/197574 – DerMike Apr 11 '12 at 10:56
  • \@anyone, Please ping me when a lib is available. Thank you so very much in advance! –  Jan 17 '14 at 19:55

7 Answers7

24

No.

You could use a while loop instead.

Iterator iterator = list.iterator();
while(iterator.hasNext()) {
    ...
}
ThomasRS
  • 8,215
  • 5
  • 33
  • 48
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
13

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;
   }
}
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • 1
    guess foreach is not that elegant after all. – TJ- Apr 11 '12 at 10:56
  • It's a tool for a certain kind of tasks. – DerMike Apr 11 '12 at 10:57
  • 2
    @TJ-: Actually, I'd say that doing one thing only makes it *more* elegant. The C-like for loop that lumps iteration, initialization and arbitrarily complex conditions and iteration steps together in one super-powerful construct, only to be used in exactly the same way 95% of the cases *that* is horribly inelegant. – Michael Borgwardt Apr 11 '12 at 10:59
8

No, foreach is specially designed only for iterating all the elements of an array or collection.

If you want you can check condition inside it and use break keyword for getting out of loop in middle.

Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
3

In Java 8, you can do it. For example :

foos.forEach(foo -> {
        if(try) {
          --your code--
        }
    });
Shubham A.
  • 2,446
  • 4
  • 36
  • 68
  • Too easy to provide a -1 without any explanation. – Shubham A. Sep 26 '16 at 13:58
  • 1
    because you just put the condition inside the loop body. In Java 8 the original question will like: Is it possible for Java 8 foreach to have conditions? For example: `foos.forEach(try, foo -> { --your code-- });`, where `try` is Predicate. – foal Oct 17 '16 at 16:31
  • that's very Scala like! for(x <- c; if cond) yield {...} – Jules0707 Jul 02 '18 at 06:18
3

The closest thing you can get is probably to filter the initial iterable:

for(Foo foo : filter(foos)) {
    //Do something
}  

Where the filter method returns an iterable containing only those elements for which your condition holds. For example with Guava you could write the filter method like this:

Iterable<String> filter(Iterable<String> foos) {
    return Iterables.filter(foos, 
            input -> input.equals("whatever");
}
michid
  • 10,536
  • 3
  • 32
  • 59
3

for-each cannot have conditions, here is the equivalent of what you asked for:

Iterator<Foo> iterator = foos.iterator();
while(iterator.hasNext() &&  condition == true) {
    //Do something
}
Bob Yoplait
  • 2,421
  • 1
  • 23
  • 35
1

You can use combination of stream, filter and forEach.

For example:

    List<String> collection = Arrays.asList("foo", "bar", "baz");

    collection.stream()
    .filter(e-> !"bar".equals(e))
    .forEach(System.out::println);

You get:

foo
baz

P.S. This will work on Java 8 and later.