Java Arraylist Removeif
# Java ArrayList removeIf() Method
[ Java ArrayList](#)
The removeIf() method is used to remove all elements of the ArrayList that satisfy a given condition.
The syntax for the removeIf() method is:
arraylist.removeIf(Predicate filter)
**Note:** arraylist is an object of the ArrayList class.
**Parameter Description:**
* filter - A filter that determines whether an element should be removed.
### Return Value
Returns true if any elements were removed.
### Example
The following example demonstrates the use of the removeIf() method:
## Example
import java.util.*;
class Main {
public static void main(String[] args){
// Create an ArrayList
ArrayList sites =new ArrayList();
sites.add("Google");
sites.add("");
sites.add("Taobao");
System.out.println("ArrayList : "+ sites);
// Remove elements containing "Tao"
sites.removeIf(e -> e.contains("Tao"));;
System.out.println("ArrayList after removal: "+ sites);
}
}
The output of the above program is:
ArrayList : [Google, , Taobao]ArrayList after removal: [Google, ]
In the example above, we used the [Java String contains() method](#) to check if an element contains "Tao".
e -> e.contains("land") returns true if the element contains "land".
**removeIf()** deletes the element if **e -> e.contains("land")** returns true.
Deleting even numbers:
## Example
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// Create an ArrayList
ArrayList 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);
// Remove all even numbers
numbers.removeIf(e ->(e %2)==0);;
System.out.println("Odd Numbers: "+ numbers);
}
}
The output of the above program is:
Numbers: [1, 2, 3, 4, 5, 6]Odd Numbers: [1, 3, 5]
In the example above, we created an ArrayList named numbers.
Note the expression:
numbers.removeIf(e -> (e % 2) == 0);
e -> (e % 2) == 0) is a lambda expression for an anonymous function. It checks if an element is divisible by 2.
To learn more about anonymous functions, visit (#).
The **removeIf()** method deletes the element if **e -> (e % 2) == 0** returns true.
[ Java ArrayList](#)
YouTip