In this tutorial, we will learn about the Java ArrayList removeIf() method, and learn how to use this method to remove those elements that pass through a given filter or pass the given predicate, with the help of examples.

Java ArrayList removeIf() method

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

Syntax

The syntax of removeIf() method is

removeIf(Predicate<? super E> filter)

where

ParameterDescription
filterThe predicate which returns true for elements to be removed.

Returns

The method returns boolean value.

ADVERTISEMENT

1. removeIf() – Remove items that satisfy a given filter

In this example, we will use ArrayList removeIf() method to remove all of the elements from the ArrayList that has a string length of 3.

Java Program

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Predicate;

public class Example {
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>(
				Arrays.asList("abc", "ab", "cde", "defg", "abcd", "eee"));		
		
		Predicate<String> filter = str -> (str.length() == 3);
		
		System.out.println("Original ArrayList          : " + arrayList);
		boolean value = arrayList.removeIf(filter);
		System.out.println("Returned value : " + value);
		System.out.println("ArrayList after removeIf()  : " + arrayList);
	}
}

Output

Original ArrayList          : [abc, ab, cde, defg, abcd, eee]
Returned value : true
ArrayList after removeIf()  : [ab, defg, abcd]

2. removeIf() – Remove odd numbers from ArrayList

In this example, we will use ArrayList removeIf() method to remove all of the elements from the ArrayList that are odd numbers.

Java Program

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Predicate;

public class Example {
	public static void main(String[] args) {
		ArrayList<Integer> arrayList = new ArrayList<Integer>(
				Arrays.asList(1,2, 3, 4, 5, 6, 7, 8));		
		
		Predicate<Integer> filter = n -> (n%2 == 1);
		
		System.out.println("Original ArrayList          : " + arrayList);
		boolean value = arrayList.removeIf(filter);
		System.out.println("Returned value : " + value);
		System.out.println("ArrayList after removeIf()  : " + arrayList);
	}
}

Output

Original ArrayList          : [1, 2, 3, 4, 5, 6, 7, 8]
Returned value : true
ArrayList after removeIf()  : [2, 4, 6, 8]

Conclusion

In this Java Tutorial, we have learnt the syntax of Java ArrayList removeIf() method, and also learnt how to use this method with the help of examples.