Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
Asked Answered
D

31

1301

We all know you can't do the following because of ConcurrentModificationException:

for (Object i : l) {
    if (condition(i)) {
        l.remove(i);
    }
}

But this apparently works sometimes, but not always. Here's some specific code:

public static void main(String[] args) {
    Collection<Integer> l = new ArrayList<>();

    for (int i = 0; i < 10; ++i) {
        l.add(4);
        l.add(5);
        l.add(6);
    }

    for (int i : l) {
        if (i == 5) {
            l.remove(i);
        }
    }

    System.out.println(l);
}

This, of course, results in:

Exception in thread "main" java.util.ConcurrentModificationException

Even though multiple threads aren't doing it. Anyway.

What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?

I'm also using an arbitrary Collection here, not necessarily an ArrayList, so you can't rely on get.

Darkling answered 21/10, 2008 at 23:23 Comment(1)
Note to readers: do have a read of docs.oracle.com/javase/tutorial/collections/interfaces/…, it may have an easier way to achieve what you want to do.Penthea
A
1672

Iterator.remove() is safe, you can use it like this:

List<String> list = new ArrayList<>();

// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
//     Iterator<String> iterator = list.iterator();
//     while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
    }
}

Note that Iterator.remove() is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Source: docs.oracle > The Collection Interface


And similarly, if you have a ListIterator and want to add items, you can use ListIterator#add, for the same reason you can use Iterator#remove — it's designed to allow it.


In your case you tried to remove from a list, but the same restriction applies if trying to put into a Map while iterating its content.

Attainture answered 21/10, 2008 at 23:27 Comment(18)
What if you want to remove an element other than the element returned in the current iteration?Hesketh
You have to use the .remove in the iterator and that is only able to remove the current element, so no :)Attainture
Be aware that this is slower compared to using ConcurrentLinkedDeque or CopyOnWriteArrayList (at least in my case)Nail
@Josh It does work fine for me. Just using it now for a collection of WebElement objects.Nitrogenous
Is it not possible to put the iterator.next() call in the for-loop? If not, can someone explain why?Vidda
It is possible to put another iterator.next() call in the for-loop, but you will also have to add another check using iterator.hasNext() to make sure you even have another element to retrieve.Reproachful
Can anyone comment how good is this way of deleting an element from a list if my list has a million elements and there are lots of possibilities of running out of java heap space?Reber
If it is a linked list you should be great. If it is an array list then you are in troubleAttainture
Iterator.remove() is an optional operation, so it is not necessarily safe (or implemented) for all container iteratorsEbullition
@GonenI It's implemented for all iterators from collections which aren't immutable. List.add is "optional" in that same sense too, but you wouldn't say it's "unsafe" to add to a list.Drypoint
As of Java 8, this approach is built-in as l.removeIf(i -> condition(i));, see https://mcmap.net/q/36532/-iterating-over-and-removing-from-a-map-duplicateCannery
I'm using this approach and still get a ConcurrentModificationException. Can someone explain to me why this is?Chinkiang
@bill-k Why you verify if the string is empty? if (string.isEmpty())Camarillo
@Camarillo it is just a condition...the example shown is to remove empty strings. I didn’t write it, so many people have edited this question—look at the history for fun. Personally I liked my original answer, it was like two lines, but I guess it’s important to be as clear as possible with such a popular answerAttainture
Is this still the recommended way in 2021?Tetrasyllable
@marticztn If you need to remove an object (or objects) from a collection inside a loop, then yes, however these days I would personally use the streaming api and filter it as the first step. This leaves the collection untouched (So it doesn't solve the "Remove it" problem, but it does let you use the collection without that data), and you could collect it into a new collection perhaps. This would be way less performant because it would make a copy of the entire collection, however the streaming API has some big benefits when it comes to threading--I guess it's up to you and your use case.Attainture
Iterators are not always helpful when another thread also modifies the collection. I had tried many ways but then realized traversing the collection manually is much safer (backward for removal)Apparition
@SaeedIr If you are reading from a different thread than you are modifying from, you should be using one of the high-performance threadsafe collecitons instead. You cannot ever trust "Manual" synchronization of threads, you must use java constructs to lock out other threads while you are modifying one--because of multiple CPUs and caching, how a normal collection works while being manipulated by another thread is not guaranteed.Attainture
D
360

This works:

Iterator<Integer> iter = l.iterator();
while (iter.hasNext()) {
    if (iter.next() == 5) {
        iter.remove();
    }
}

I assumed that since a foreach loop is syntactic sugar for iterating, using an iterator wouldn't help... but it gives you this .remove() functionality.

Darkling answered 21/10, 2008 at 23:26 Comment(2)
foreach loop is syntactic sugar for iterating. However as you pointed out, you need to call remove on the iterator - which foreach doesn't give you access to. Hence the reason why you can't remove in a foreach loop (even though you are actually using an iterator under the hood)Shed
+1 for example code to use iter.remove() in context, which Bill K's answer does not [directly] have.Singleness
S
243

With Java 8 you can use the new removeIf method. Applied to your example:

Collection<Integer> coll = new ArrayList<>();
//populate

coll.removeIf(i -> i == 5);

A simple test as example:

    @Test
    public void testRemoveIfOneList() {
        List<String> outer = new ArrayList<>();
        outer.add("one");
        outer.add("two");
        outer.add("three");

        outer.removeIf(o -> o.length() == 3);

        assertEquals(1, outer.size());
    }

It even works when you compare two lists and want to remove from both.

    @Test
    public void testRemoveIfTwoLists() {
        List<String> outer = new ArrayList<>();
        outer.add("one");
        outer.add("two");
        outer.add("three");
        List<String> inner = new ArrayList<>();
        inner.addAll(outer);

        // first, it removes from inner, and if anything is removed, then removeIf() returns true,
        // leading to removing from outer
        outer.removeIf(o -> inner.removeIf(i -> i.equals(o)));

        assertEquals(0, outer.size());
        assertEquals(0, inner.size());
    }

However, if one of the list has duplicates, make sure it's iterated in the inner loop, because for inner list, it will remove all elements meeting the criteria, but for outer list, when any element is removed, it will return immediately and stops checking.

This test will fail:

    @Test
    public void testRemoveIfTwoListsInnerHasDuplicates() {
        List<String> outer = new ArrayList<>();
        outer.add("one");
        outer.add("one");
        outer.add("two");
        outer.add("two");
        outer.add("three");
        outer.add("three");
        List<String> inner = new ArrayList<>();
        inner.addAll(outer); // both have duplicates

        // remove all elements from inner(executed twice), then remove from outer
        // but only once! if anything is removed, it will return immediately!!
        outer.removeIf(o -> inner.removeIf(i -> i.equals(o)));

        assertEquals(0, inner.size()); // pass, inner all removed
        assertEquals(0, outer.size()); // will fail, outer has size = 3
    }
Salicaceous answered 28/5, 2014 at 10:11 Comment(6)
Ooooo! I was hoping something in Java 8 or 9 might help. This still seems rather verbose to me, but I still like it.Gallicism
Is implementing equals() recommended in this case too?Clovah
by the way removeIf uses Iterator and while loop. You can see it at java 8 java.util.Collection.javaCaboodle
@Caboodle Some implementations like ArrayList override it for performance reasons. The one you are referring to is only the default implementation.Kosygin
@AnmolGupta: No, equals is not used at all here, so it doesn't have to be implemented. (But of course, if you use equals in your test then it has to be implemented the way you want it.)Outwards
This should be the accepted answer now, this will be applicable and desirable for most people looking at the answers here.Multiplex
C
44

Since the question has been already answered i.e. the best way is to use the remove method of the iterator object, I would go into the specifics of the place where the error "java.util.ConcurrentModificationException" is thrown.

Every collection class has a private class which implements the Iterator interface and provides methods like next(), remove() and hasNext().

The code for next looks something like this...

public E next() {
    checkForComodification();
    try {
        E next = get(cursor);
        lastRet = cursor++;
        return next;
    } catch(IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
    }
}

Here the method checkForComodification is implemented as

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

So, as you can see, if you explicitly try to remove an element from the collection. It results in modCount getting different from expectedModCount, resulting in the exception ConcurrentModificationException.

Corves answered 15/5, 2010 at 19:57 Comment(1)
Very interesting. Thank you! I often don't call remove() myself, I instead favour clearing the collection after iterating through it. Not to say that's a good pattern, just what I've been doing lately.Gallicism
B
28

You can either use the iterator directly like you mentioned, or else keep a second collection and add each item you want to remove to the new collection, then removeAll at the end. This allows you to keep using the type-safety of the for-each loop at the cost of increased memory use and cpu time (shouldn't be a huge problem unless you have really, really big lists or a really old computer)

public static void main(String[] args)
{
    Collection<Integer> l = new ArrayList<Integer>();
    Collection<Integer> itemsToRemove = new ArrayList<>();
    for (int i=0; i < 10; i++) {
        l.add(Integer.of(4));
        l.add(Integer.of(5));
        l.add(Integer.of(6));
    }
    for (Integer i : l)
    {
        if (i.intValue() == 5) {
            itemsToRemove.add(i);
        }
    }

    l.removeAll(itemsToRemove);
    System.out.println(l);
}
Belicia answered 21/10, 2008 at 23:32 Comment(6)
this is what i normally do, but the explicit iterator is a more elgant solution i feel.Darkling
Fair enough, as long as you aren't doing anything else with the iterator - having it exposed makes it easier to do things like call .next() twice per loop etc. Not a huge problem, but can cause issues if you are doing anything more complicated than just running through a list to delete entries.Belicia
@RodeoClown: in the original question, Claudiu is removing from the Collection, not the iterator.Lutyens
Removing from the iterator removes from the underlying collection... but what I was saying in the last comment is that if you are doing anything more complicated than just looking for deletes in the loop (like processing correct data) using the iterator can make some errors easier to make.Belicia
If it is a simple delete values that aren't needed and the loop is only doing that one thing, using the iterator directly and calling .remove() is absolutely fine.Belicia
using Iterator.remove() only works on the current value provided by the iterator. If you have some condition in your loop that requires removal of some other member of the collection, then RodeoClown's solution is the way to go.Skied
H
19

In such cases a common trick is (was?) to go backwards:

for(int i = l.size() - 1; i >= 0; i --) {
  if (l.get(i) == 5) {
    l.remove(i);
  }
}

That said, I'm more than happy that you have better ways in Java 8, e.g. removeIf or filter on streams.

Homogeny answered 29/8, 2014 at 9:56 Comment(4)
This is a good trick. But it wouldn't work on non-indexed collections like sets, and it'd be really slow on say linked lists.Darkling
@Darkling Yes, this is definitely just for ArrayLists or similar collections.Homogeny
I'm using an ArrayList, this worked perfectly, thanks.Outman
indexes are great. If it's so common why don't you use for(int i = l.size(); i-->0;) {?Soutane
K
17

Same answer as Claudius with a for loop:

for (Iterator<Object> it = objects.iterator(); it.hasNext();) {
    Object object = it.next();
    if (test) {
        it.remove();
    }
}
Kevinkevina answered 21/8, 2013 at 12:39 Comment(0)
G
12

With Eclipse Collections, the method removeIf defined on MutableCollection will work:

MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.lessThan(3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);

With Java 8 Lambda syntax this can be written as follows:

MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.cast(integer -> integer < 3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);

The call to Predicates.cast() is necessary here because a default removeIf method was added on the java.util.Collection interface in Java 8.

Note: I am a committer for Eclipse Collections.

Germano answered 18/12, 2012 at 23:8 Comment(0)
C
11

Make a copy of existing list and iterate over new copy.

for (String str : new ArrayList<String>(listOfStr))     
{
    listOfStr.remove(/* object reference or index */);
}
Culbert answered 26/6, 2012 at 5:28 Comment(5)
Making a copy sounds like a waste of resources.Kevinkevina
@Kevinkevina That depends on the size of the list and the density of the objects within. Still a valuable and valid solution.Penalize
I have been using this method. It takes a bit more resource, but much more flexible and clear.Literally
This is a good solution when you are not intending to remove objects inside the loop itself, but they are rather "randomly" removed from other threads (e.g. network operations updating data). If you find yourself doing these copies a lot there is even a java implementation doing exactly this: docs.oracle.com/javase/8/docs/api/java/util/concurrent/…Dunn
Making a copy of the list is what they are typically doing with listeners on Android. It's a valid solution for small lists.Foucquet
P
10

With a traditional for loop

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

for (int i = 0; i < myArray.size(); ) {
    String text = myArray.get(i);
    if (someCondition(text))
        myArray.remove(i);
    else
        i++;   
}
Player answered 16/4, 2017 at 20:29 Comment(3)
Ah, so its really just the enhanced-for-loop that throws the Exception.Deontology
FWIW - same code would still work after modified to increment i++ in the loop guard rather than within loop body.Deontology
Correction ^: That is if the i++ incrementing were not conditional - I see now that's why you do it in the body :)Deontology
S
10

People are asserting one can't remove from a Collection being iterated by a foreach loop. I just wanted to point out that is technically incorrect and describe exactly (I know the OP's question is so advanced as to obviate knowing this) the code behind that assumption:

for (TouchableObj obj : untouchedSet) {  // <--- This is where ConcurrentModificationException strikes
    if (obj.isTouched()) {
        untouchedSet.remove(obj);
        touchedSt.add(obj);
        break;  // this is key to avoiding returning to the foreach
    }
}

It isn't that you can't remove from the iterated Colletion rather that you can't then continue iteration once you do. Hence the break in the code above.

Apologies if this answer is a somewhat specialist use-case and more suited to the original thread I arrived here from, that one is marked as a duplicate (despite this thread appearing more nuanced) of this and locked.

Soutane answered 17/3, 2018 at 11:2 Comment(0)
B
5

ConcurrentHashMap or ConcurrentLinkedQueue or ConcurrentSkipListMap may be another option, because they will never throw any ConcurrentModificationException, even if you remove or add item.

Beige answered 23/6, 2016 at 11:18 Comment(2)
Yep, and note that those are all in java.util.concurrent package. Some other similar/common-use-case classes from that package are CopyOnWriteArrayList & CopyOnWriteArraySet [but not limited to those].Deontology
Actually, I just learned that although those data structure Objects avoid ConcurrentModificationException, using them in an enhanced-for-loop can still cause indexing problems (i.e: still skipping elements, or IndexOutOfBoundsException...)Deontology
S
4

Another way is to use a copy of your arrayList just for iteration:

List<Object> l = ...
    
List<Object> iterationList = ImmutableList.copyOf(l);
    
for (Object curr : iterationList) {
    if (condition(curr)) {
        l.remove(curr);
    }
}
Stardom answered 14/3, 2019 at 11:18 Comment(2)
Note: i isn't a index but instead the object. Maybe calling it obj would be more fitting.Bowstring
Was already suggested above back in 2012:https://mcmap.net/q/36388/-iterating-through-a-collection-avoiding-concurrentmodificationexception-when-removing-objects-in-a-loop Making a copy of the list is what they are typically doing with listeners on Android. It's a valid solution for small lists.Foucquet
G
3

A ListIterator allows you to add or remove items in the list. Suppose you have a list of Car objects:

List<Car> cars = ArrayList<>();
// add cars here...

for (ListIterator<Car> carIterator = cars.listIterator();  carIterator.hasNext(); )
{
   if (<some-condition>)
   { 
      carIterator().remove()
   }
   else if (<some-other-condition>)
   { 
      carIterator().add(aNewCar);
   }
}
Glendaglenden answered 13/10, 2017 at 15:16 Comment(1)
The additional methods in the ListIterator interface (extension of Iterator) are interesting - particularly its previous method.Deontology
M
2

Now, You can remove with the following code

l.removeIf(current -> current == 5);
Moreira answered 22/9, 2020 at 14:22 Comment(0)
A
1

I know this question is too old to be about Java 8, but for those using Java 8 you can easily use removeIf():

Collection<Integer> l = new ArrayList<Integer>();

for (int i=0; i < 10; ++i) {
    l.add(new Integer(4));
    l.add(new Integer(5));
    l.add(new Integer(6));
}

l.removeIf(i -> i.intValue() == 5);
Actuality answered 26/9, 2018 at 20:15 Comment(0)
S
1

Java Concurrent Modification Exception

  1. Single thread
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String value = iter.next()
    if (value == "A") {
        list.remove(it.next()); //throws ConcurrentModificationException
    }
}

Solution: iterator remove() method

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String value = iter.next()
    if (value == "A") {
        it.remove()
    }
}
  1. Multi thread
  • copy/convert and iterate over another one collection. For small collections
  • synchronize[About]
  • thread safe collection[About]
Stuyvesant answered 31/3, 2021 at 14:1 Comment(2)
A condensed but more comprehensive answer.Dulcy
Your first example is not equivalent to your second, or to the OP's code.Flew
E
0

I have a suggestion for the problem above. No need of secondary list or any extra time. Please find an example which would do the same stuff but in a different way.

//"list" is ArrayList<Object>
//"state" is some boolean variable, which when set to true, Object will be removed from the list
int index = 0;
while(index < list.size()) {
    Object r = list.get(index);
    if( state ) {
        list.remove(index);
        index = 0;
        continue;
    }
    index += 1;
}

This would avoid the Concurrency Exception.

Electrocorticogram answered 19/11, 2013 at 9:18 Comment(3)
The question explicitly states, that the OP is not necessary using ArrayList and thus cannot rely on get(). Otherwise probably a good approach, though.Coppery
(Clarification ^) OP is using an arbitraryCollection - Collection interface does not include get. (Although FWIW List interface does include 'get').Deontology
I just added a separate, more detailed Answer here also for while-looping a List. But +1 for this Answer because it came first.Deontology
W
0
for (Integer i : l)
{
    if (i.intValue() == 5){
            itemsToRemove.add(i);
            break;
    }
}

The catch is the after removing the element from the list if you skip the internal iterator.next() call. it still works! Though I dont propose to write code like this it helps to understand the concept behind it :-)

Cheers!

Woolfell answered 30/6, 2016 at 7:24 Comment(0)
H
0

The best way (recommended) is use of java.util.concurrent package. By using this package you can easily avoid this exception. Refer Modified Code:

public static void main(String[] args) {
    Collection<Integer> l = new CopyOnWriteArrayList<Integer>();
    
    for (int i=0; i < 10; ++i) {
        l.add(new Integer(4));
        l.add(new Integer(5));
        l.add(new Integer(6));
    }
    
    for (Integer i : l) {
        if (i.intValue() == 5) {
            l.remove(i);
        }
    }
    
    System.out.println(l);
}
Hostage answered 3/5, 2018 at 17:59 Comment(2)
Did you take into account the performance hit? Each time you "write" to this structure, it's contents will be copied to a new object. All this is bad for performance.Countrywoman
It isn't the best way and it isn't recommended. Don't use quote formatting for text that isn't quoted. If it is quoted, provide a citation.Flew
M
0

Example of thread safe collection modification:

public class Example {
    private final List<String> queue = Collections.synchronizedList(new ArrayList<String>());

    public void removeFromQueue() {
        synchronized (queue) {
            Iterator<String> iterator = queue.iterator();
            String string = iterator.next();
            if (string.isEmpty()) {
                iterator.remove();
            }
        }
    }
}
Moser answered 17/9, 2018 at 9:3 Comment(0)
D
0

I know this question assumes just a Collection, and not more specifically any List. But for those reading this question who are indeed working with a List reference, you can avoid ConcurrentModificationException with a while-loop (while modifying within it) instead if you want to avoid Iterator (either if you want to avoid it in general, or avoid it specifically to achieve a looping order different from start-to-end stopping at each element [which I believe is the only order Iterator itself can do]):

*Update: See comments below that clarify the analogous is also achievable with the traditional-for-loop.

final List<Integer> list = new ArrayList<>();
for(int i = 0; i < 10; ++i){
    list.add(i);
}

int i = 1;
while(i < list.size()){
    if(list.get(i) % 2 == 0){
        list.remove(i++);

    } else {
        i += 2;
    }
}

No ConcurrentModificationException from that code.

There we see looping not start at the beginning, and not stop at every element (which I believe Iterator itself can't do).

FWIW we also see get being called on list, which could not be done if its reference was just Collection (instead of the more specific List-type of Collection) - List interface includes get, but Collection interface does not. If not for that difference, then the list reference could instead be a Collection [and therefore technically this Answer would then be a direct Answer, instead of a tangential Answer].

FWIWW same code still works after modified to start at beginning at stop at every element (just like Iterator order):

final List<Integer> list = new ArrayList<>();
for(int i = 0; i < 10; ++i){
    list.add(i);
}

int i = 0;
while(i < list.size()){
    if(list.get(i) % 2 == 0){
        list.remove(i);

    } else {
        ++i;
    }
}
Deontology answered 19/12, 2018 at 23:40 Comment(3)
This still requires very careful calculation of indicies to remove, however.Bladdernose
Also, this is just a more detailed explanation of this answer https://mcmap.net/q/36388/-iterating-through-a-collection-avoiding-concurrentmodificationexception-when-removing-objects-in-a-loopBladdernose
Good to know - thanks! That other Answer helped me understand that it's the enhanced-for-loop that would throw ConcurrentModificationException, but not the traditional-for-loop (which the other Answer uses) - not realizing that before is why I was motivated to write this Answer (I erroneously thought then that it was all for-loops that would throw the Exception).Deontology
S
0

One solution could be to rotate the list and remove the first element to avoid the ConcurrentModificationException or IndexOutOfBoundsException

int n = list.size();
for(int j=0;j<n;j++){
    //you can also put a condition before remove
    list.remove(0);
    Collections.rotate(list, 1);
}
Collections.rotate(list, -1);
Sommers answered 31/7, 2019 at 20:16 Comment(0)
P
0

Try this one (removes all elements in the list that equal i):

for (Object i : l) {
    if (condition(i)) {
        l = (l.stream().filter((a) -> a != i)).collect(Collectors.toList());
    }
}
Paw answered 13/11, 2019 at 19:15 Comment(0)
S
0

You can use a while loop.

Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
    Map.Entry<String, String> entry = iterator.next();
    if(entry.getKey().equals("test")) {
        iterator.remove();
    } 
}
Strained answered 28/12, 2020 at 10:40 Comment(1)
The point here is not the while loop but removing via the Iterator.Flew
J
0

I ended up with this ConcurrentModificationException, while iterating the list using stream().map() method. However the for(:) did not throw the exception while iterating and modifying the the list.

Here is code snippet , if its of help to anyone: here I'm iterating on a ArrayList<BuildEntity> , and modifying it using the list.remove(obj)

 for(BuildEntity build : uniqueBuildEntities){
            if(build!=null){
                if(isBuildCrashedWithErrors(build)){
                    log.info("The following build crashed with errors ,  will not be persisted -> \n{}"
                            ,build.getBuildUrl());
                    uniqueBuildEntities.remove(build);
                    if (uniqueBuildEntities.isEmpty()) return  EMPTY_LIST;
                }
            }
        }
        if(uniqueBuildEntities.size()>0) {
            dbEntries.addAll(uniqueBuildEntities);
        }
Janson answered 3/7, 2021 at 19:11 Comment(0)
B
0

If using HashMap, in newer versions of Java (8+) you can select each of 3 options:

public class UserProfileEntity {
    private String Code;
    private String mobileNumber;
    private LocalDateTime inputDT;
    // getters and setters here
}
HashMap<String, UserProfileEntity> upMap = new HashMap<>();


// remove by value
upMap.values().removeIf(value -> !value.getCode().contains("0005"));

// remove by key
upMap.keySet().removeIf(key -> key.contentEquals("testUser"));

// remove by entry / key + value
upMap.entrySet().removeIf(entry -> (entry.getKey().endsWith("admin") || entry.getValue().getInputDT().isBefore(LocalDateTime.now().minusMinutes(3)));
Brough answered 28/11, 2021 at 9:17 Comment(0)
A
0

Iterators are not always helpful when another thread also modifies the collection. I had tried many ways but then realized traversing the collection manually is much safer (backward for removal):

for (i in myList.size-1 downTo 0) {
    myList.getOrNull(i)?.also {
       if (it == 5)
          myList.remove(it)
    }
}
Apparition answered 23/11, 2022 at 6:46 Comment(0)
A
-1

In case ArrayList:remove(int index)- if(index is last element's position) it avoids without System.arraycopy() and takes not time for this.

arraycopy time increases if(index decreases), by the way elements of list also decreases!

the best effective remove way is- removing its elements in descending order: while(list.size()>0)list.remove(list.size()-1);//takes O(1) while(list.size()>0)list.remove(0);//takes O(factorial(n))

//region prepare data
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Integer> toRemove = new ArrayList<Integer>();
Random rdm = new Random();
long millis;
for (int i = 0; i < 100000; i++) {
    Integer integer = rdm.nextInt();
    ints.add(integer);
}
ArrayList<Integer> intsForIndex = new ArrayList<Integer>(ints);
ArrayList<Integer> intsDescIndex = new ArrayList<Integer>(ints);
ArrayList<Integer> intsIterator = new ArrayList<Integer>(ints);
//endregion

// region for index
millis = System.currentTimeMillis();
for (int i = 0; i < intsForIndex.size(); i++) 
   if (intsForIndex.get(i) % 2 == 0) intsForIndex.remove(i--);
System.out.println(System.currentTimeMillis() - millis);
// endregion

// region for index desc
millis = System.currentTimeMillis();
for (int i = intsDescIndex.size() - 1; i >= 0; i--) 
   if (intsDescIndex.get(i) % 2 == 0) intsDescIndex.remove(i);
System.out.println(System.currentTimeMillis() - millis);
//endregion

// region iterator
millis = System.currentTimeMillis();
for (Iterator<Integer> iterator = intsIterator.iterator(); iterator.hasNext(); )
    if (iterator.next() % 2 == 0) iterator.remove();
System.out.println(System.currentTimeMillis() - millis);
//endregion
  • for index loop: 1090 msec
  • for desc index: 519 msec---the best
  • for iterator: 1043 msec
Azure answered 4/2, 2016 at 17:25 Comment(0)
H
-2

you can also use Recursion

Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.

Hives answered 4/6, 2020 at 13:23 Comment(0)
D
-3

this might not be the best way, but for most of the small cases this should acceptable:

"create a second empty-array and add only the ones you want to keep"

I don't remeber where I read this from... for justiness I will make this wiki in hope someone finds it or just to don't earn rep I don't deserve.

David answered 21/10, 2008 at 23:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.