Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a such thing as a while each loop in Java?

If there were such a thing I would imagine the syntax to be something along the lines of

while(Integer item : group<Integer>; item > 5)
{
    //do something
}

Just wondering if there was something like this or a way to imitate this?

like image 386
Bobby Avatar asked Jun 30 '09 22:06

Bobby


1 Answers

No, the closest would be:

for (Integer item : group<Integer>)
{
    if (item <= 5)
    {
        break;
    }
    //do something
}

Of course if Java ever gets concise closures, it would be reasonable to write something like .NET's Enumerable.TakeWhile method to wrap the iterable (group in this case) and make it finish early if the condition stops holding.

That's doable even now of course, but the code to do it would be ugly. For reference, the C# would look like this:

foreach (int item in group.TakeWhile(x => x > 5))
{
    // do something
}

Maybe Java will get nice closures some time...

like image 198
Jon Skeet Avatar answered Oct 12 '22 23:10

Jon Skeet