Best way to remove element from list or why they kept iterator without this option

I’m studing apex now and dont understand the situation with list and iterator.
In java you cant delete in any way elements from list while iterating it.
So therefore developers added iterator and also added removeAll method to list.
Here are some examples.

Deleting element by using another list in java:

    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);

    List<Integer> listToRemove = new ArrayList<Integer>();

    for (Integer num : list) {
        if (num==1){
            listToRemove.add(num);
        }
    }

    list.removeAll(listToRemove);
    System.out.println(list);

Result: [2, 3]

Deleting element by using iterator in java:

    Iterator<Integer> iterator = list.iterator();

    while(iterator.hasNext()){
        if(iterator.next() == 1){
            iterator.remove();
        }
    }
    System.out.println(list);

Result: [2, 3]

Ok, then i decided to do the same on apex.

Firstly, i didn’t find removeAll method for list. Bad luck 🙂

Then i found iterator and thought that logic is the same as in java, but got this:

Method does not exist or incorrect signature:
[Iterator].remove()

Almost the same, they kept hasNext(), next(), but they did not keep a remove() method.
Why? 🙂

Then i tried to do something like this:

Iterator<Integer> iter = li.iterator();   Integer count = 0;

while(iter.hasNext()){
    Integer temp = iter.next();    
    if(temp == 1){
        li.remove(count);
    }
    count++;   
}   
System.debug(li);

It doesn’t work also.

So the only way that works for me is:

    for (Integer i = 0; i < li.size(); i++) {
        if (li.get(i) == 1){
            li.remove(i);
            i--;
        }
    }

Can you please share with me with the best way of removing elements form list!?
Thanks in advance!

Answer

The idiomatic way to do this in other languages without iterator semantics is to iterate through the list backwards.

For example:

public static List<Object> removeAll(List<Object> target, Object toRemove) {
    for(Integer i = target.size() - 1; i >= 0; i--) {
        if(target[i].equals(toRemove)) {
            target.remove(i);
        }
    }

    return target;
}

Attribution
Source : Link , Question Author : Bogdan K , Answer Author : Alex Tennant

Leave a Comment