Remove list from list Java
This post will discuss how to remove elements from a mutable list in Java that satisfies the given predicate.
1. Using an iteratorThe Iterator interface provides the remove() method, which removes the last element returned by the iterator. The idea is to get an iterator to the given list and use the remove() method to remove elements on which the predicate is satisfied.
2. Using removeAll() methodWe can maintain a separate collection containing elements from the original list that matches the given predicate. Then we can use the removeAll() method provided by the List interface to remove elements of that collection from the original list.
3. Using Java 8In Java 8, we can use Stream to remove elements from a list by filtering the stream easily. ⮚ Using Collectors The idea is to convert the specified list to a sequential Stream, filter the stream and accumulate the elements that match the given predicate into a new list using a Collector.
⮚ Using forEach() with List.add() This is similar to the earlier approach, where we maintain a separate collection containing the elements from the original list that matches the given predicate and using the List.removeAll() method to remove those elements from the original list.
⮚ Using forEach() with List.remove() Since we cant modify a list while iterating over it, we can create a duplicate list and remove elements that satisfy the predicate from the original list by iterating over the duplicate list. The following code uses Java 8 Stream to do the filtering, but we can also use an iterator or a for-each loop.
⮚ Using removeIf() The List interface provides the removeIf() method that removes all the list elements that satisfy the given predicate. This is the simplest approach among all approaches discussed above and uses Iterator.remove() behind the scenes.
Thats all about removing elements from a list that satisfies a given predicate in Java.
|