ArrayList removeIf() method in java

Let’s learn ArrayList removeIf() method in java.

ArrayList removeIf() method in java

removeIf() method of ArrayList class removes all of the elements of this collection that satisfy the given predicate.

Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller.

Syntax:

public boolean removeIf(Predicate <? super Integer>filter)

Parameters:

filter a predicate which returns true for elements to beremoved.

Returns:

true if any elements were removed.

Throws:

NullPointerException – if the specified filter is null.

Also read – ArrayList in java

Now let’s see example on ArrayList removeIf() method.

import java.util.ArrayList;
public class ArrayListRemoveIfMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(15);
      al.add(8);
      al.add(58);
      al.add(19);
      // remove numbers divisible by 2
      al.removeIf(n -> (n % 2 == 0));
      // print list
      for(int a : al)
      {
         System.out.println(a);
      }
   }
}


Output:

15
19


Let’s see another example on ArrayList removeIf() method.

import java.util.ArrayList;
public class ArrayListRemoveIfMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("Jackal");
      al.add("Tiger");
      al.add("Lion");
      al.add("Elephant");
      al.add("Leopard");
      // remove animal names that start with L
      al.removeIf(n -> (n.charAt(0) == 'L'));
      System.out.println("Animal names that does not start with L: ");
      for(String str : al)
      {
         System.out.println(str);
      }
   }
}


Output:

Animal names that does not start with L:
Jackal
Tiger
Elephant