English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList removeIf() method deletes all elements that meet the specified conditions from the ArrayList.
The syntax of removeIf() method is:
arraylist.removeIf(Predicate<E> filter)
filter - to decide whether to delete the element
Note:If the filter returns true, delete the element.
If an element is removed from the arraylist, it returns true.
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create an ArrayList ArrayList<Integer> numbers = new ArrayList<>(); //Add elements to the ArrayList numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5); numbers.add(6); System.out.println("Numbers: ") + numbers); //Delete all even numbers numbers.removeIf(e -> (e % 2) == 0); System.out.println("Odd numbers: ") + numbers); } }
Output Result
Numbers: [1, 2, 3, 4, 5, 6] Odd numbers: [1, 3, 5]
In the above example, we created an ArrayList named numbers. Note this line,
numbers.removeIf(e -> (e % 2) == 0);
Here,
e -> (e % 2) == 0) - is a lambda expression. It checks if the element is divisible by2Divisible. For more information, please visitJava Lambda Expressions.
removeIf() - If e -> (e % 2) == 0 returns true, then delete the element.
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create an ArrayList ArrayList<String> countries = new ArrayList<>(); //Add elements to the ArrayList countries.add("Iceland"); countries.add("America"); countries.add("Ireland"); countries.add("Canada"); countries.add("Greenland"); System.out.println("Country: " + countries); //Delete all countries with 'land' in their name countries.removeIf(e -If e.contains("land"));; System.out.println("Countries without "land": "); + countries); } }
Output Result
Countries: [Iceland, America, Ireland, Canada, Greenland] Countries without "land": [America, Canada]
In the above example, we usedJava String contains()method to check if the element contains"land". Here,
e -If e.contains("land") - If the element contains "land", then return true
removeIf() - If e-If e.contains("land") returns true, then delete the element.