.removeIf()
Anonymous contributor
Published Mar 12, 2024
Contribute to Docs
The .removeIf()
method removes all the elements of an ArrayList
that satisfy a given predicate. Any error or runtime exception thrown during the iteration or by the predicate is relayed to the caller. If any element is removed, this method returns true
. Otherwise, it returns false
.
Syntax
arrayListInstance.removeIf(Predicate<T> filter);
arrayListInstance
: The name of theArrayList
to be checked.Predicate<T>
: A functional interface representing a condition that takes a single argument of typeT
.filter
: The condition that needs to be checked.
Example
In the following example, the .removeIf()
method removes all the even elements from an ArrayList
called nums
:
import java.util.ArrayList;public class Main {public static void main(String[] args) {ArrayList<Integer> nums = new ArrayList<Integer>();nums.add(10);nums.add(15);nums.add(20);nums.add(30);nums.removeIf(n -> (n % 2 == 0));System.out.println(nums);}}
Here is the output for the above example:
[15]
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours