Refactoring a nested loop

Posted by user3517441 on Stack Overflow See other posts from Stack Overflow or by user3517441
Published on 2014-06-11T21:16:13Z Indexed on 2014/06/11 21:24 UTC
Read the original article Hit count: 142

Filed under:
|

I have the following code which I use a lot of times in the class.

for (int i = 0; i < someList.size(); i++) {
    for (int j = 0; j < someList.size(); j++) {
        if (i != j) {
            someList.get(i).sendMessageTo(someList.get(j))); //variable action
        }
    }
}

The purpose of the loop is to make each element in the List to send a message (or perform another action) to every element in the list except itself.

Is there any way I can create a helper method so I don't have to repeat the loop code.

I want to be able to state the variable action and call the helper method.

Thanks.

© Stack Overflow or respective owner

Related posts about java

Related posts about loops