Remove Elements from ArrayList in Java

In this quick article, we’re going to talk about two simple ways to remove items from Java ArrayList that match certain predicates.

1. Removing Elements with Iterator

Let's use Iterator to iterate over ArrayList and check for elements equality and remove matching elements from ArrayList:
package com.javaguides.corejava.collections;

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

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

        List < String > courses = new ArrayList < > ();
        courses.add("C");
        courses.add("C++");
        courses.add("Java");
        courses.add("Java EE");
        courses.add("Spring");
        courses.add("Hibernate");

        System.out.println("Before removing elements :: " + courses);
        Iterator < String > iterator = courses.iterator();
        while (iterator.hasNext()) {
            String course = (String) iterator.next();
            if ("Java".equals(course)) {
                iterator.remove();
            }
        }
        System.out.println("After removing elements :: " + courses);
    }
}
Output:
Before removing elements :: [C, C++, Java, Java EE, Spring, Hibernate]
After removing elements :: [C, C++, Java EE, Spring, Hibernate]

2. Java 8 and Collection.removeIf()

Java 8 introduced a new method to the Collection interface that provides a more concise way to remove elements using Predicate:
package com.javaguides.corejava.collections;

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

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

        List < String > courses2 = new ArrayList < > ();
        courses2.add("C");
        courses2.add("C++");
        courses2.add("Java");
        courses2.add("Java EE");
        courses2.add("Spring");
        courses2.add("Hibernate");

        System.out.println("Java 8 Before removing elements :: " + courses2);
        // using Collection.removeIf()
        courses2.removeIf(course - > "Java".equals(course));
        System.out.println("Java 8 After removing elements :: " + courses2);
    }
}
Output:
Java 8 Before removing elements :: [C, C++, Java, Java EE, Spring, Hibernate]
Java 8 After removing elements :: [C, C++, Java EE, Spring, Hibernate]
It’s important to note that contrary to the Iterator approach, removeIf performs similarly well in both LinkedList and ArrayList.
In Java 8, ArrayList overrides the default implementation – which relies on Iterator – and implements a different strategy: first, it iterates over the elements and marks the ones that match our Predicate; afterward, it iterates a second time to remove (and shift) the elements that were marked in the first iteration.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments