Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing items from a list [duplicate]

While looping through a list, I would like to remove an item of a list depending on a condition. See the code below.

This gives me a ConcurrentModification exception.

for (Object a : list) {     if (a.getXXX().equalsIgnoreCase("AAA")) {         logger.info("this is AAA........should be removed from the list ");         list.remove(a);     } } 

How can this be done?

like image 686
Techie Avatar asked Jun 24 '13 15:06

Techie


People also ask

How do you remove duplicates from a list in Python?

To remove the duplicates from a list, you can make use of the built-in function set(). The specialty of the set() method is that it returns distinct elements. You can remove duplicates from the given list by importing OrderedDictfrom collections.

How do I avoid duplicates in my list?

If you don't want duplicates, use a Set instead of a List . To convert a List to a Set you can use the following code: // list is some List of Strings Set<String> s = new HashSet<String>(list); If really necessary you can use the same construction to convert a Set back into a List .


1 Answers

for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {     String a = iter.next();     if (...) {         iter.remove();     } } 

Making an additional assumption that the list is of strings. As already answered, an list.iterator() is needed. The listIterator can do a bit of navigation too.

–---------

Update

As @AyushiJain commented, there is

list.removeIf(...); 
like image 139
Joop Eggen Avatar answered Oct 06 '22 07:10

Joop Eggen