67

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?

5

12 Answers 12

86

In your case, there's no need to iterate through the list, because you know which object to delete. You have several options. First you can remove the object by index (so if you know, that the object is the second list element):

 a.remove(1);       // indexes are zero-based

Or, you can remove the first occurence of your string:

 a.remove("acbd");  // removes the first String object that is equal to the
                    // String represented by this literal

Or, remove all strings with a certain value:

 while(a.remove("acbd")) {}

It's a bit more complicated, if you have more complex objects in your collection and want to remove instances, that have a certain property. So that you can't remove them by using remove with an object that is equal to the one you want to delete.

In those case, I usually use a second list to collect all instances that I want to delete and remove them in a second pass:

 List<MyBean> deleteCandidates = new ArrayList<>();
 List<MyBean> myBeans = getThemFromSomewhere();

 // Pass 1 - collect delete candidates
 for (MyBean myBean : myBeans) {
    if (shallBeDeleted(myBean)) {
       deleteCandidates.add(myBean);
    }
 }

 // Pass 2 - delete
 for (MyBean deleteCandidate : deleteCandidates) {
    myBeans.remove(deleteCandidate);
 }
Sign up to request clarification or add additional context in comments.

6 Comments

removeAll takes a collection so you would need to so list.removeAll(Arrays.asList("acbd"));
Ooops ;) I'll change that.
+1, List has a removeAll(Collection obj) method, so you could just use myBeans.removeAll(deleteCandidates); instead of iterating through deleteCandidate list.
-1 you havent considerd the point about removeAll, looping through array and deleting is looking horrible. especialy when you have a.remove in a while statement. Awfull practice in terms of clearness.
@Andreas_D To add to your comment, if items in the List are of integer type, your method of removing will throw exception. E.g. Mylist=[2,3,5], try removing 5 by Mylist.remove(5).
|
62

One-liner (java8):

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

(does all the iterating implicitly)

3 Comments

Also helps with removing objects, depending on one attribute like so: list.removeIf(obj -> obj.getAttribute().equals(otherObj.getAttribute()));
You can shorten this to list.removeIf("abcd"::equals);.
@SamuelPhilipp how to do it if I have list of object? I have list.removeIf(s -> "abcd".equals(s.getName()));
15

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.

6 Comments

I would use "abcd".equals(value) to avoid NullPointerExceptions because a List can contain null values. Note that with the 'break' you are explicitly removing only the first occurrence with value "abcd".
@AdriaanKoster: Yes you are correct. I have ammended my answer. Also, regarding the break, the OP did not mention the possibility of duplicate elements. If there are duplicates, then yes the break would need to be removed.
I agree that OP did not specify how many instances should be removed. I added a comment to the question.
@AdriaanKoster: Regarding your second point, I have never come accross this issue. Would doing a a.remove(new String("acbd")) work?
@AdriaanKoster: So how would you go about it? Do you intern all the strings while you are iterating over them?. Also, thanks for the upvote ;)
|
9

for java8 we can simply use removeIf function like this

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

1 Comment

Careful with this - .equals() worked for me while == did not.
4

You should check API for these questions.

You can use remove methods.

a.remove(1);

OR

a.remove("acbd");

Comments

2

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]

Comments

1

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.

Comments

1

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

Comments

0

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

Comments

0

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

Comments

0

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]

Comments

0

a.removeIf(x -> a.contains("testString"));

Just to add who is looking for partial matching.

Comments

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.