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?
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.
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 .
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.
–---------
As @AyushiJain commented, there is
list.removeIf(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With