eduardohl
eduardohl

Reputation: 1216

How to modify all elements except the current one when iterating

I have list of Comments that contains a list of Tags.

I want to iterate over my list of Comments, and if one comment has a Tag DEPRECATE_OTHERS, I want to add a tag DEPRECATED to ALL other comments.

So far I've been able to come up with a too cluttered solution, but I'm wondering if there's some facility that could help me make it cleaner:

    for (int i = 0; i < comments.size(); i++) {
        Comment comment = comments.get(i);
        for (Tag tag : comment.getTags()) {
            if(MyEnum.DEPRECATE_OTHERS.equals(tag)) {
                for(int j = 0; j < comments.size(); j++) {
                    if(j != i) {
                        comments.get(j).getTags().add(MyEnum.DEPRECATED)
                    }
                }
            }
        }
    }

OBS: I might have multiple DEPRECATE_OTHERS and I'd like to add multiple DEPRECATED flags in that case

Upvotes: 1

Views: 50

Answers (2)

Dave Morrissey
Dave Morrissey

Reputation: 4411

There are a few methods you could use to simplify this code. Using for each iteration, Collection.contains() and object equality you could get it down to this:

for (Comment comment : comments) {
    if(comment.getTags().contains(MyEnum.DEPRECATE_OTHERS))) {
        for (Comment otherComment : comments) {
            if (otherComment != comment) {
                otherComment.getTags().add(MyEnum.DEPRECATED)
            }
        }
    }
}

As Adam says, two separate iterations would be neater still.

Upvotes: 2

Adam Yost
Adam Yost

Reputation: 3625

set a flag, something like deprecate_others_id = -1; When you find a DEPRECATE_OTHERS tag, set that variable to the index, and while that var is not -1, set each tag to DEPRECATE_OTHERS. At the end of your iteration, start a new loop from the beginning which iterates until it reaches deprecate_others_id, marking all those along the way.

This makes use of the fact you are currently iterating anyway, only making you circle back for the tags before the one which initiated Deprecate_Others

int deprecate_others_id = -1;
int numtags = 0;
for (int i = 0; i < comments.size(); i++) {
    Comment comment = comments.get(i);
    if(deprecate_others_id != -1){
        while(comment.getNumberofDepTags < numtags){
           comment.addTag(DEPRECATED);
        }
    }
    for (Tag tag : comment.getTags()) {
        if(MyEnum.DEPRECATE_OTHERS.equals(tag)) {
            deprecate_others_id = Math.max(deprecate_others_id,i);
        }
    }
}
if(deprecate_others_id != -1){
    for(int i=0; i<deprecate_others_id; i++){
      Comment comment = comments.get(i);
      while(comment.getNumberofDepTags < numtags){
           comment.addTag(DEPRECATED);
      }
    }
}

Upvotes: 0

Related Questions