3

Is it possible to nest foreach statements in java and start the nested statement at the current index that the outer foreach loop is at?

So if I have

List<myObj> myObjList = new ArrayList<myObj>();

for (myObj o : myObjList){
    // how do I start the nested for loop at the current spot in the list?
    for(

}

Thanks!

1
  • You should recheck that acceptance. Tim S is doing exactly what you're asking for. And the basic idea can be applied without the use of a sublist by accessing by index. Commented May 28, 2013 at 23:08

3 Answers 3

6

Here's a way to do it by keeping track of the index yourself, then using subList to start the inner loop at the right spot:

int i = 0;
for (myObj o1 : myObjList) {
    for (myObj o2 : myObjList.subList(i, myObjList.size())) {
        // do something
    }
    i++;
}

I think this is clearer than using basic for loops, but that's certainly debatable. However, both should work, so the choice is yours. Note that if you are using a collection that does not implement List<E>, this will not work (subList is defined on List<E> as the idea of an "index" really only makes sense for lists).

Sign up to request clarification or add additional context in comments.

Comments

6

No. Enhanced for loops conceal the current index of the loop. You need to use a basic for loop which uses an index.

2 Comments

is there another way to accomplish this?
Use an index based loop rather than an enhanced for loop
1

While you could do something like this, it would be extremely sub-optimal. Consider that the indexOf method would be iterating across the entire list (again!) to find the object. Note also that it depends on myObjList being an ordered collection (list):

List<myObj> myObjList = new ArrayList<myObj>();

for (myObj o : myObjList){
    int idx = myObjList.indexOf(o);
    for(myObj blah : myObjList.subList(idx, myObjList.size()) {
        ...
    }

}

far better:

int myObjListSize = myObjList.size();
for (int outerIndex = 0; outerIndex < myObjListSize ; outerIndex++){
    for(int innerIndex = outerIndex; innerIndex < myObjListSize ; innerIndex++) {
        myObj o = myObjList.get(innerIndex);
    }

}

other note: class myObj should be capitalized to class MyObj to adhere to Java naming standards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.