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
?
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
?
No.
You could use a while loop instead.
Iterator iterator = list.iterator();
while(iterator.hasNext()) {
...
}
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;
}
}
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.
In Java 8
, you can do it. For example :
foos.forEach(foo -> {
if(try) {
--your code--
}
});
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");
}
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
}
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.