Java ArrayList.removeAll() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about ArrayList.removeAll() method. boolean java.util.ArrayList.removeAll(Collection<?> c) removes from this list all of its elements that are contained in the specified collection.

syntax

Removes from this list all of its elements that are contained in the specified collection.

boolean java.util.ArrayList.removeAll(Collection<?> c)

Parameter

c collection containing elements to be removed from this list.

Return

true if this list changed as a result of the call

Return

ClassCastException - If the class of an element of this list is incompatible with the specified collection

NullPointerException - If this list contains a null element or if the specified collection is null.

Java ArrayList.removeAll() example

Refer below steps

  • Constructs two ArrayList with an initial capacity using new ArrayList<String>().
  • Add some elements in colors and removeColors ArrayList using add() method.
  • Call removeAll() method on colors ArrayList. It removes all the elements from this (colors) list that are contained in the specified collection. It return true if elements are removed from the list otherwise return false.
package com.technicalkeeda.app;

import java.util.ArrayList;

public class ArrayListRemoveAll {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> ();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("White");
        colors.add("Pink");

        ArrayList <String> removeColors = new ArrayList <String> ();
        removeColors.add("Green");
        removeColors.add("Blue");

        for (String color: colors) {
            System.out.println("colors before removeAll:- " + color);
        }

        System.out.println("\nList removeAll() ? " + colors.removeAll(removeColors) + "\n");

        for (String color: colors) {
            System.out.println("colors after removeAll:- " + color);
        }

    }
}

Output

colors before removeAll:- Red
colors before removeAll:- Green
colors before removeAll:- Blue
colors before removeAll:- White
colors before removeAll:- Pink

List removeAll() ? true

colors after removeAll:- Red
colors after removeAll:- White
colors after removeAll:- Pink


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0305 seconds.