Java remove elements from collection by filtering

One of the way to remove elements of collection (in this example list) is to use method removeIf

Method declaration:

default boolean removeIf(Predicate<? super E> filter)

Description: Removes all of the elements of this collection that satisfy the given predicate. Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller. Implementation

Requirements: The default implementation traverses all elements of the collection using its iterator(). Each matching element is removed using Iterator.remove(). If the collection’s iterator does not support removal then an UnsupportedOperationException will be thrown on the first matching element.

Parameters: filter – a predicate which returns true for elements to be removed

Returns: true if any elements were removed

Important: this method modify the collection which is used on. Good practice is to create another collection which will be modified and leave the initial (original) untouched so can be used later in the code.

In this example we create list of number and later on we use removeIf with Predicate which filter only the odd numbers.

import java.util.ArrayList;
import java.util.List;

public class MainRemoveIf {

    public static void main(String[] args) {
        List<Integer> initList = List.of(1, 2, 3, 4, 5, 6);
        // "initList" is immutable and removeIf modify the list, so
        // we create another list "result" and
        // use removeIf on that list
        List<Integer> result = new ArrayList<>(initList);

        // Leave only the odd numbers
        result.removeIf(e -> e % 2 == 0 );
        System.out.println(result);
    }
}

Output:

[1, 3, 5]

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.