views:

192

answers:

3

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?

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

This is what I can think of.

Soldier.moth
Exactly my suggestion, except that your condition looks like it's the wrong way round to me.
Jon Skeet
Looks right, doesn't it?
WowtaH
thanks Jon Skeet, fixed it
Soldier.moth
It's fine now - it was originally "if (item > 5)"
Jon Skeet
So he asked and answered his own question all in 4 minutes? :P
WowtaH
Yep. Can't figure out what's wrong with it.
ojrac
I can figure out a way to do most things, what I'm left wondering is whether it is the best way, if there were a such thing as a while each loop that would have been better. I figured I would let the votes decide if I had a decent approach to my problem.
Soldier.moth
+6  A: 

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...

Jon Skeet
Hehe. Beat me by a few seconds again. btw...I think you intended the to use 'for' instead of 'while' in the first line of your code snippet.
Brandon E Taylor
Hm. I don't recognize that while syntax.
ojrac
Doh! Yes, for indeed. c'n'p error
Jon Skeet
+2  A: 

For reference, Jon Skeet's second answer in Java would currently, for some interface Predicate, look something like:

for (int item : takeWhile(group, new Predicate<Integer>() {
    public boolean contains(Integer x) {
        return x > 5;
    }
}) {
    // do something
}

It's the syntax that sucks, not the semantics.

Tom Hawtin - tackline
thanks I was wondering about that, that syntax definitely sucks
Soldier.moth
+1 for suckiness
voyager