CollectionUtils removeAll() Example in Java

In this post we will see CollectionUtils removeAll() example in Java. we will see how to use CollectionUtils removeAll() method. The removeAll() method has below syntax. Fisrt parameter we need to pass the main list and second parameter we need to give the list we want to remove.

public static <E> Collection<E> removeAll(Collection<E> mainList, Collection<?> listNeedToRemve)

We need to add the below dependency in maven to use org.apache.commons.lang3.CollectionUtils removeAll() method. We can download the apache-commons maven dependency from here.

pom.xml changes


CollectionUtils removeAll() Example in Java

package com.javatute;

import org.apache.commons.collections4.CollectionUtils;

import java.util.*;

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

        List<String> firstList = new ArrayList<>();

        List<String> secondList = new ArrayList<>();
        List<String> newList = (List<String>) CollectionUtils.removeAll(firstList, secondList);

Output is

[Mike, Tom]

In the above example, in output, we can see that Jon and mark has been removed.

How to use CollectionUtis removeAll() method with custom type of object.

We need to override equals() and hashcode() methods and the removeAll() method should be able to remove the custom type of element.

How do I remove all elements from a collection in Java?

The CollectionUtils removeAll() method remove all elements in the list including null and empty. We can also use list.removeAll()method.

Note – Internally CollectionsUtil removeAll() uses ListUtils removeAll() method.

That’s all about CollectionUtils removeAll() Example in Java.

Related post