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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.*; class Main { public static void main(String arg[]) { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Adrian"); names.add("Charlie"); names.removeIf(name -> name.startsWith("A") && name.length() > 5); for (String name : names) { System.out.println(name); } } } |
Output:
1 2 3 4 5 | Alice Bob Charlie |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.*; class Main { public static void main(String arg[]) { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Adrian"); names.add("Charlie"); names.removeIf(name -> name.startsWith("A") || name.endsWith("e")); for (String name : names) { System.out.println(name); } } } |
Output:
1 2 3 | Bob |
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.