Java Foreach with a condition

后端 未结 6 2034
一个人的身影
一个人的身影 2020-12-18 18:27

Is it possible for Java foreach to have conditions?

For example,

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

Is t

相关标签:
6条回答
  • 2020-12-18 18:42

    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.

    0 讨论(0)
  • 2020-12-18 18:42

    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
    }
    
    0 讨论(0)
  • 2020-12-18 18:43

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

    foos.forEach(foo -> {
            if(try) {
              --your code--
            }
        });
    
    0 讨论(0)
  • 2020-12-18 18:45

    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");
    }
    
    0 讨论(0)
  • 2020-12-18 18:48

    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;
       }
    }
    
    0 讨论(0)
  • 2020-12-18 19:00

    No.

    You could use a while loop instead.

    Iterator iterator = list.iterator();
    while(iterator.hasNext()) {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题