Java ArrayList removeAll() Method Example

Java ArrayList removeAll() Method removes from this list all of its elements that are contained in the specified collection (optional operation).

In this example, we use the removeAll() method to remove scripting Languages from programming Languages:

Java ArrayList removeAll() Method Example

package com.javaguides.collections.arraylistexamples;

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

public class RemoveElementsFromArrayListExample {
    public static void main(String[] args) {
        List < String > programmingLanguages = new ArrayList < > ();
        programmingLanguages.add("C");
        programmingLanguages.add("C++");
        programmingLanguages.add("Java");
        programmingLanguages.add("Kotlin");
        programmingLanguages.add("Python");
        programmingLanguages.add("Perl");
        programmingLanguages.add("Ruby");

        System.out.println("Initial List: " + programmingLanguages);

        // Remove all the elements that exist in a given collection
        List < String > scriptingLanguages = new ArrayList < > ();
        scriptingLanguages.add("Python");
        scriptingLanguages.add("Ruby");
        scriptingLanguages.add("Perl");

        programmingLanguages.removeAll(scriptingLanguages);
        System.out.println("After removeAll(scriptingLanguages): " + programmingLanguages);

        System.out.println("After Removing all elements that start with \"C\": " + programmingLanguages);
    }
}

Output

Initial List: [C, C++, Java, Kotlin, Python, Perl, Ruby]
After removeAll(scriptingLanguages): [C, C++, Java, Kotlin]
After Removing all elements that start with "C": [C, C++, Java, Kotlin]

Reference

Java ArrayList Source Code Examples


Comments