Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove objects from an ArrayList based on a given criteria

Tags:

java

arraylist

I would like to remove an element from an ArrayList in Java if it meets a certain criteria.

ie:

for (Pulse p : pulseArray) {
    if (p.getCurrent() == null) {
        pulseArray.remove(p);
    }
}

I can understand why this does not work, but what is a good way to do this?

like image 381
user1724416 Avatar asked Nov 09 '12 21:11

user1724416


People also ask

How can we remove an Object from ArrayList?

There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows: Using remove() method by indexes(default) Using remove() method by values. Using remove() method over iterators.

Which method is used to eliminate elements based on criteria?

The 'filter' method is used to eliminate elements based on a criteria.

How do you remove multiple objects from an ArrayList in Java?

Core Java bootcamp program with Hands on practice The List provides removeAll() method to remove all elements of a list that are part of the collection provided.

How do I remove a specific item from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.


2 Answers

You can use Collection::removeIf(Predicate filter) (available from Java8 onwards), here is a simple example:

final Collection<Integer> list = new ArrayList<>(Arrays.asList(1, 2));
list.removeIf(value -> value < 2);
System.out.println(list); // outputs "[2]"
like image 179
Markus Schulte Avatar answered Sep 21 '22 05:09

Markus Schulte


You must use an Iterator to iterate and the remove function of the iterator (not of the list) :

Iterator<Pulse> iter = pulseArray.iterator();
while (iter.hasNext()) {
  Pulse p = iter.next();
  if (p.getCurrent()==null) iter.remove();
}

Note that the Iterator#remove function is said to be optionnal but it is implemented by the ArrayList's iterator.

Here's the code of this concrete function from ArrayList.java :

765         public void remove() {
766             if (lastRet < 0)
767                 throw new IllegalStateException();
768             checkForComodification();
769 
770             try {
771                 ArrayList.this.remove(lastRet);
772                 cursor = lastRet;
773                 lastRet = -1;
774                 expectedModCount = modCount;
775             } catch (IndexOutOfBoundsException ex) {
776                 throw new ConcurrentModificationException();
777             }
778         }
779 
780         final void checkForComodification() {
781             if (modCount != expectedModCount)
782                 throw new ConcurrentModificationException();
783         }
784     }

The expectedModCount = modCount; line is why it won't throw an exception when you use it while iterating.

like image 31
Denys Séguret Avatar answered Sep 19 '22 05:09

Denys Séguret