Remove Elements from ArrayList based on Filter

To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.

Following is a quick code example to remove the elements from ArrayList based on filter.

boolean b = arraylist_1.removeIf(predicate);

Example – Remove Elements from ArrayList based on Predicate

In the following program, we shall take an ArrayList of strings, and remove all the elements that pass through a filter or satisfy the specified condition. The filter is that the string ends with “a”.

Java Program

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
	public static void main(String[] args) {
		ArrayList<String> arraylist_1 = new ArrayList<String>(
				Arrays.asList("apple", "banana", "mango", "orange", "papaya", "plum"));
				
		arraylist_1.removeIf(element -> (element.endsWith("a")));
		
		arraylist_1.forEach(element -> {
			System.out.println(element);
		});
		
	}
}

Output

apple
mango
orange
plum
ADVERTISEMENT

Conclusion

In this Java Tutorial, we learned how to remove all elements from the ArrayList present in the given range, using sublist() and clear() method.