简体   繁体   中英

Android: removing elements from list with iterator

     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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM