[java] How to remove element from ArrayList by checking its value?

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

for eg.

ArrayList<String> a=new ArrayList<String>();
a.add("abcd");
a.add("acbd");
a.add("dbca");

I know we can iterate over arraylist, and .remove() method to remove element but I dont know how to do it while iterating. How can I remove element which has value "acbd", that is second element?

This question is related to java collections arraylist

The answer is


Try below code :

 public static void main(String[] args) throws Exception{
     List<String> l = new ArrayList<String>();
     l.add("abc");
     l.add("xyz");
     l.add("test");
     l.add("test123");
     System.out.println(l);
     List<String> dl = new ArrayList<String>();
    for (int i = 0; i < l.size(); i++) {
         String a = l.get(i);
         System.out.println(a); 
         if(a.equals("test")){
             dl.add(a);
         }
    }
    l.removeAll(dl);
     System.out.println(l); 
}

your output :

 [abc, xyz, test, test123]
abc
xyz
test
test123
[abc, xyz, test123]

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


for java8 we can simply use removeIf function like this

listValues.removeIf(value -> value.type == "Deleted");

This will give you the output,

    ArrayList<String> l= new ArrayList<String>();

    String[] str={"16","b","c","d","e","16","f","g","16","b"};
    ArrayList<String> tempList= new ArrayList<String>();

    for(String s:str){
        l.add(s);
    }

    ArrayList<String> duplicates= new ArrayList<String>();

    for (String dupWord : l) {
        if (!tempList.contains(dupWord)) {
            tempList.add(dupWord);
        }else{
            duplicates.add(dupWord);
        }
    }

    for(String check : duplicates){
        if(tempList.contains(check)){
            tempList.remove(check);
        }
    }

    System.out.println(tempList);

output,

[c, d, e, f, g]

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();
    }

One-liner (java8):

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

(does all the iterating implicitly)


You should check API for these questions.

You can use remove methods.

a.remove(1);

OR

a.remove("acbd");

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.


Just use myList.remove(myObject).

It uses the equals method of the class. See http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(java.lang.Object)

BTW, if you have more complex things to do, you should check out the guava library that has dozen of utility to do that with predicates and so on.


Snippet to remove a element from any arraylist based on the matching condition is as follows:

List<String> nameList = new ArrayList<>();
        nameList.add("Arafath");
        nameList.add("Anjani");
        nameList.add("Rakesh");

Iterator<String> myItr = nameList.iterator();

    while (myItr.hasNext()) {
        String name = myItr.next();
        System.out.println("Next name is: " + name);
        if (name.equalsIgnoreCase("rakesh")) {
            myItr.remove();
        }
    }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable