Remove all occurrences of an element from ArrayList

前端 未结 5 1097
傲寒
傲寒 2021-01-31 07:00

I am using java.util.ArrayList, I want to remove all the occurrences of a particular element.

    List l = new ArrayList         


        
相关标签:
5条回答
  • 2021-01-31 07:36

    You can use the removeAll() method.

    list.removeAll(Arrays.asList("someDuplicateString"));
    
    0 讨论(0)
  • 2021-01-31 07:37

    Another way using Java 8:

    l.removeIf("first"::equals);
    
    0 讨论(0)
  • 2021-01-31 07:41
    l.removeAll(Collections.singleton("first"));
    
    0 讨论(0)
  • 2021-01-31 07:55
    while(l.remove("first")) { }
    

    This removes all elements "first" from the list.

    0 讨论(0)
  • 2021-01-31 08:00

    Since in your example you are using Strings I guess did should do the trick.

    for(int i = 0; i < list.size();i++){
        if(list.get(i).equals(someStringNameOrValue)){
            list.remove(i--);
        }
    }
    

    Looks like I misunderstood your question. I updated my answer. Am I right? you want to remove all occurrences of "first" ?

    0 讨论(0)
提交回复
热议问题