0
     private void removeLettersFromMakeWords(List<String> a, List<String> b){
     Iterator<String> i = a.iterator();

     for(String s:b)
         while (i.hasNext()) {
            Object o = i.next();

            if(o.toString().equals(s)){
                i.remove();
                break;
            }
         }
    }

I use an iterator to loop through my list and remove an element from the list if there is a match. For example: if a = [a, y, f, z, b] and b = [a, f] --> the output will be a = [y, z, b]

Problem is if a = [a, y, f, z, b] and b = [f, a] --> the output will be a = [a, y, z, b] and the iterator doesn't remove the [a] value in the beginning. Is there a way to reset the iterator so that every time I break the iterator starts from the beginning? Or is there a better way to solve this issue?

2
  • 2
    The issue is that you never reset the iterator. You could simply create a new iterator for each string of b. However, I would recommend to simply use a.removeAll(b) instead of all that code. Commented Nov 4, 2014 at 17:02
  • thanks that is much easier Commented Nov 4, 2014 at 17:27

1 Answer 1

2

You cannot "reset" an iterator, but you can just get a new one whenever you want to iterate from the beginning again. Like this:

if (o.toString().equals(s)) {
     i.remove();
     i = a.iterator();
     break;
}

Edit: as @njzk2 says in his comment, there are better (built-in) methods for doing this.

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

2 Comments

this is great! and ya the removeAll is much simpler
@user2456977 Indeed. However, since the subject was "removing elements from list with iterator"... :)

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.