Skip to content
Advertisement

Having two for loop in a single Java Method

I have a method shown in the code below, I have a hashmap buffer and queue with several list in both. I want to search a particular message to set it true when it is stable; the message could be in either the buffer or queue. is it alright to lump the two for loop within a single method? or is there a better way to put the method to reflect my intention.

so if the message is in the buffer, it is set to true, if not it checks the queue; if not found it returns false

public static boolean SetMessageToStable(int event_actor, Message msg) {
        if (mBuffer.get(event_actor) != null) {
            for (int i = 0; i < mBuffer.get(event_actor).size(); i++) { // iterate the list of event actor to find matching message
                if (mBuffer.get(event_actor).get(i).equals(msg)) {
                    mBuffer.get(event_actor).get(i).setMsg_stable(true); // set stable if found
                    return true;
                }
            }
        }
        if (DQ.get(event_actor) != null) {
            for (int i = 0; i < DQ.get(event_actor).size(); i++) {  // search the event actor's DQ if the message has not been found
                if (DQ.get(event_actor).get(i).equals(msg)) {
                    DQ.get(event_actor).get(i).setMsg_stable(true); // set stable if found
                    return true;
                }
            }
        }
        return false;
    }

Advertisement

Answer

Is it alright to lump the two for loop within a single method?

Sure.

Is there a better way to put the method to reflect my intention?

The two loops are identical with the exception of the specific map that is being evaluated (DQ vs mBuffer). You could easily do this:

public static boolean SetMessageToStable(int event_actor, Message msg) {
    return SetMessageToStableInternal(mBuffer, event_actor, msg)
        || SetMessageToStableInternal(DQ, event_actor, msg);
}

private static boolean SetMessageToStableInternal(
        Map<Integer, List<Message>> map,
        int event_actor,
        Message msg
) {
    List<Message> msgList = map.get(event_actor);
    if (msgList != null) {
        for (int i = 0; i < msgList.size(); i++) {
            Message m = msgList.get(i);
            if (m.equals(msg)) {
                m.setMsg_stable(true);
                return true;
            }
        }
    }
    return false;
}

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement