Remove objects from an ArrayList based on a given criteria

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]"

When you are removing the element from the same list, the index gets disturbed. Try little differently as below:

  for (int i=0; i < pulseArray.size(); i++) {
     Pulse p = (Pulse)pulseArray.get(i);
     if (p.getCurrent() == null) {
        pulseArray.remove(p);
        i--;//decrease the counter by one
     }
  }

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.


No need to use iterator. With Java 8 (streaming and filtering capability and lambdas) you can accomplish it using one line. For eg. the required code that does the operation you specified will be :

pulseArray = pulseArray.stream().filter(pulse -> pulse != null).collect(Collectors.toList());

Tags:

Java

Arraylist