Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring a nested loop

Tags:

java

loops

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.

Edit: I need just one helper method to take care of the for loop and the if algorithm. I will supply the List and the whatever action I need to use. It should work for all.

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

Thanks.

like image 909
ecthelion84 Avatar asked Jan 25 '26 09:01

ecthelion84


1 Answers

You could do something like (I don't know what type is in your List, I called it Element):

public interface ApplySomeAction
{
    public apply(Element e1, Element e2);
}

...

public void applyActionToAllElements(ApplySomeAction action)
{
    for (int i = 0; i < someList.size(); i++) {
       for (int j = 0; j < someList.size(); j++) {
           if (i != j) {
               action.apply(someList.get(i), someList.get(j));
           }
       }
    }
}

later call it with:

applyActionToAllElements(new ApplySomeAction() {
    public apply(Element e1, Element e2)
    {
        e1.sendMessageTo(e2));
    }
};

Could make another interface+method with just one element if you often do an action with just one of those elements.

like image 71
NESPowerGlove Avatar answered Jan 27 '26 23:01

NESPowerGlove



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!