Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

arraylist
removeif
java
communitycreator

What is ArrayList.removeIf() method in Java?

Programming Bytes

The removeIf method will loop through all the elements of the list and remove the elements that match the condition of the predicatePredicate is a functional interface, which takes one argument and returns either true or false based on the condition defined. function, which is sent as the argument to the removeIf method.

Syntax

public boolean removeIf(Predicate<? super E> filter);

Example

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 predicatePredicate is a functional interface, which takes one argument and returns either true or false based on the condition defined. function to call the 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.

Example with a list of objects

main.java
User.java
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 predicatePredicate is a functional interface, which takes one argument and returns either true or false based on the condition defined. function to call the 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 Userclass. If the predicate function returns true, the current object will be removed from the users list.

RELATED TAGS

arraylist
removeif
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring