The removeIf
method will loop through all the elements of the list and remove the elements that match the condition of the removeIf
method.
public boolean removeIf(Predicate<? super E> filter);
import java.util.ArrayList;class RemoveIf {public static void main( String args[] ) {ArrayList<Integer> numbers = new ArrayList<>();numbers.add(1);numbers.add(-10);numbers.add(30);numbers.add(-3);System.out.println("The numbers list is " + numbers);numbers.removeIf(number -> number < 0);System.out.println("After removing negative elements, the numbers list is => " + numbers);}}
In the code above, we created a numbers
ArrayList and added some positive and negative numbers to it.
Then, we passed a removeIf
method. The predicate function will be tested against each element of the numbers
list.
In the predicate function, we checked if the number < 0
. If the predicate function returns true
, then the current object will be removed from the list.
import java.util.ArrayList;class RemoveId {public static void main( String args[] ) {ArrayList<User> users = new ArrayList<>();users.add(new User("Ram", 15));users.add(new User("Ralph", 13));users.add(new User("Raj", 25));users.add(new User("Rahul", 24));System.out.println("The users list is");System.out.println(users);users.removeIf( user -> ! user.canVote() );System.out.println("\nAfter removing users who cannot vote, the users list is");System.out.println(users);}}
In the code above, we created a users
ArrayList and added some objects of the User
class.
Then, we passed a removeIf
method on the users
list. The predicate function will be tested against each element of the users
list.
In the predicate function, we checked if the object does not satisfy the canVote
condition defined in the User
class. If the predicate function returns true
, the current object will be removed from the users
list.