Java

How to use removeIf() with multiple conditions in Java2 min read

In this post you will learn how to use removeIf method with multiple conditions.

RemoveIf: The removeIf() method is a utility method that was introduced in Java 8 as part of the java.util.Collection interface. It allows you to remove all elements from a collection that match a specified condition.




To specify multiple conditions for the removeIf() method in Java, you can use the && operator to combine multiple predicates.

Here is an example of how to use removeIf() with multiple conditions:

Code:

Output:

In this example, the removeIf() method will remove the element “Charlie” from the names list because it starts with the letter “A” and has a length greater than 5. The resulting list will be [“Alice”, “Bob”].

You can also use the || operator to specify that an element should be removed if it meets either of two conditions.

Output:

In this example, the removeIf() method will remove the elements “Alice” and “Charlie” from the names list because they either start with the letter “A” or end with the letter “e”. The resulting list will be [“Bob”].

It’s important to note that the removeIf() method takes a Predicate as an argument. A Predicate is a functional interface that represents a boolean-valued function of one argument. In the examples above, the Predicate is a lambda expression that combines multiple conditions using the && and || operators.

Leave a Comment