How to Remove Elements from Collections using the removeIf() Method
The removeIf()
method is a default method introduced in Java 8 for the Collection
interface. It is used to remove all elements from the collection that satisfy a given condition.
The removeIf()
method takes a Predicate
as its argument, which is a functional interface that takes an element of the collection as its input and returns a boolean value indicating whether the element should be removed from the collection. If the Predicate
returns true
for an element, that element is removed from the collection.
Here's an example of how to use the removeIf()
method to remove all even numbers from a list:
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.removeIf(n -> n % 2 == 0); // removes all even numbers
System.out.println(numbers); // prints [1, 3, 5]
In this example, the removeIf()
method is used to remove all even numbers from the numbers
list. The Predicate
used is a lambda expression that checks whether the element is even by checking if it's divisible by 2 with no remainder.
Note that the removeIf()
method modifies the original collection and returns a boolean value indicating whether any elements were removed.
Here's another example of how to use the removeIf()
method with a custom Predicate
to remove all elements from a list that contain a specific substring:
javaCopy codeList<String> strings = new ArrayList<>();
strings.add("hello");
strings.add("world");
strings.add("goodbye");
strings.add("moon");
strings.removeIf(s -> s.contains("oo"));
System.out.println(strings); // prints [hello, goodbye]
In this example, the removeIf()
method is used to remove all elements from the strings
list that contain the substring "oo". The Predicate
used is a lambda expression that checks whether the element contains the substring by calling the contains()
method of the String
class.
You can create your own Predicate
by defining a class that implements the Predicate
interface, or by using a lambda expression as shown in this example. By using a custom Predicate
, you can define any condition that you want to use to filter the elements in the collection.