![]() |
VOOZH | about |
In Java, elements can be removed from a List based on a specific condition using a Predicate, which represents a true/false test. Java provides multiple efficient ways to do this, such as using an Iterator, removeAll(), Streams (Java 8), and removeIf(). These approaches help safely modify lists, avoid runtime errors, and write clean, readable code.
This approach safely removes elements while iterating over the list and avoids ConcurrentModificationException.
Example: This program shows how to remove null elements from a Java List using an Iterator and a Predicate.
List with null values: [Geeks, null, forGeeks, null, A computer portal] List with null values removed: [Geeks, forGeeks, A computer portal]
Explanation:
In this method, elements satisfying the predicate are first collected and then removed using removeAll()
Example: This program shows how to remove specific elements from a List in Java using a Predicate and the removeAll() method.
Original List: [1, 10, 15, 10, 12, 5, 10, 20] Updated List: [1, 15, 12, 5, 20]
Explanation :
Java 8 Streams provide a clean and functional way to filter elements.
Example: This Java program uses Java 8 Streams and a Predicate to efficiently remove unwanted elements, like nulls, from a list.
List with null values: [Geeks, null, forGeeks, null, A computer portal] List with null values removed: [Geeks, forGeeks, A computer portal]
Explanation:
removeIf() directly removes all elements that satisfy the given predicate.
Example:This program shows how to remove elements from a list that meet a specific condition using Java’s removeIf() method with a Predicate.
List with null values: [Geeks, null, forGeeks, null, A computer portal] List with null values removed: [Geeks, forGeeks, A computer portal]
Explanation: