How to remove element from ArrayList by checking its value?

后端 未结 11 1147
一整个雨季
一整个雨季 2020-12-01 03:47

I have ArrayList, from which I want to remove an element which has particular value...

for eg.

ArrayList a=new ArrayList         


        
相关标签:
11条回答
  • 2020-12-01 04:04

    One-liner (java8):

    list.removeIf(s -> s.equals("acbd")); // removes all instances, not just the 1st one
    

    (does all the iterating implicitly)

    0 讨论(0)
  • 2020-12-01 04:04

    use contains() method which is available in list interface to check the value exists in list or not.If it contains that element, get its index and remove it

    0 讨论(0)
  • 2020-12-01 04:05

    You would need to use an Iterator like so:

    Iterator<String> iterator = a.iterator();
    while(iterator.hasNext())
    {
        String value = iterator.next();
        if ("abcd".equals(value))
        {
            iterator.remove();
            break;
        }
    }
    

    That being said, you can use the remove(int index) or remove(Object obj) which are provided by the ArrayList class. Note however, that calling these methods while you are iterating over the loop, will cause a ConcurrentModificationException, so this will not work:

    for(String str : a)
    {
        if (str.equals("acbd")
        {
            a.remove("abcd");
            break;
        }
    }
    

    But this will (since you are not iterating over the contents of the loop):

    a.remove("acbd");
    

    If you have more complex objects you would need to override the equals method.

    0 讨论(0)
  • 2020-12-01 04:10

    You should check API for these questions.

    You can use remove methods.

    a.remove(1);
    

    OR

    a.remove("acbd");
    
    0 讨论(0)
  • 2020-12-01 04:12

    Use a iterator to loop through list and then delete the required object.

        Iterator itr = a.iterator();
        while(itr.hasNext()){
            if(itr.next().equals("acbd"))
                itr.remove();
        }
    
    0 讨论(0)
提交回复
热议问题