Tutorial

How To Use remove() Methods for Java List and ArrayList

Updated on May 2, 2025
How To Use remove() Methods for Java List and ArrayList

Introduction

Java List remove() method is used to remove elements from the list. ArrayList is the most widely used implementation of the List interface, so the examples here will use ArrayList remove() methods.

Java List remove() Methods

There are two remove() methods to remove elements from the List.

  1. E remove(int index): This method removes the element at the specified index and returns it. The subsequent elements are shifted to the left by one place. This method throws IndexOutOfBoundsException if the specified index is out of range. If the list implementations does not support this operation, UnsupportedOperationException is thrown.
  2. boolean remove(Object o) This method removes the first occurrence of the specified Object. If the list doesn’t contain the given element, it remains unchanged. This method returns true if an element is removed from the list, otherwise false. If the object is null and list doesn’t support null elements, NullPointerException is thrown. UnsupportedOperationException is thrown if the list implementation doesn’t support this method.

Let’s look into some examples of remove() methods.

1. Remove the element at a given index

This example will explore E remove(int index):

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

list.add("A");
list.add("B");
list.add("C");
list.add("C");
list.add("B");
list.add("A");

System.out.println(list);

String removedStr = list.remove(1);
System.out.println(list);
System.out.println(removedStr);

First, this code constructs and prints a list:

Output
[A, B, C, C, B, A]

Then, this code executes remove(1) to remove the element at index 1. Finally, it prints the new resulting list and also prints the removed element.

Output
[A, C, C, B, A] B

The B at index 1 has been removed.

2. IndexOutOfBoundsException with remove(int index) Method

This example will explore E remove(int index) when the index exceeds the list:

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

list.add("A");

String removedStr = list.remove(10);

This code constructs a list with a length of 1. However, when the code attempts to remove the element at index 10:

Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 10 out of bounds for length 1 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:372) at java.base/java.util.ArrayList.remove(ArrayList.java:535) at com.journaldev.java.ArrayListRemove.main(ArrayListRemove.java:19)

This attempt throws the IndexOutOfBoundsException.

3. Unmodifiable List remove() UnsupportedOperationException Example

The List.of() method creates an immutable list, which can’t be modified.

List<String> list = List.of("a", "b");

System.out.println(list);

String removedStr = list.remove(1);

System.out.println(removedStr);

First, this code constructs and prints an immutable list:

Output
[a, b]

Then the code attempts to use the remove() method to remove the element at index 1:

Output
Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) at java.base/java.util.ImmutableCollections$AbstractImmutableList.remove(ImmutableCollections.java:258) at TestRemoveList.main(TestRemoveList.java:12)

This attempt throws UnsupportedOperationException. It will also throw UnsupportedOperationException if you attempt list.remove("a") or list.remove("b").

4. Removing an object from the list

This example will explore boolean remove(Object o):

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

list.add("A");
list.add("B");
list.add("C");
list.add("C");
list.add("B");
list.add("A");

System.out.println(list);

boolean isRemoved = list.remove("C");
System.out.println(list);
System.out.println(isRemoved);

isRemoved = list.remove("X");
System.out.println(list);
System.out.println(isRemoved);

First, this code constructs and prints a list:

Output
[A, B, C, C, B, A]

Then, this code executes remove("C") to remove the first instance of C. Next, it prints the resulting list and also prints the boolean value of the operation - true:

Output
[A, B, C, B, A] true

Then, this code executes remove("X"), but there is no instance of X in the list, the list does not change. Finally, it prints the list and also prints the boolean value of the operation - false:

Output
[A, B, C, B, A] false

Practical Use Cases

Removing specific elements from user-defined lists

In many applications, you might need to remove specific elements from a list based on certain conditions. For example, in a social media platform, you might want to remove all posts from a user who has been banned. You can use the remove() method to achieve this. Here’s an example:

List<Post> posts = new ArrayList<>();
// Assuming posts is populated with user posts

// Remove all posts from a banned user
String bannedUserId = "bannedUser123";
posts.removeIf(post -> post.getUserId().equals(bannedUserId));

Cleaning up filtered lists in web/backend applications

When processing data in web or backend applications, you might need to filter out certain elements from a list based on specific criteria. The remove() method can be used to clean up the list after filtering. For instance, in an e-commerce platform, you might want to remove all products that are out of stock from a list of products to be displayed to customers. Here’s an example:

List<Product> products = new ArrayList<>();
// Assuming products is populated with all products

// Remove all out-of-stock products from the list
products.removeIf(Product::isOutOfStock);

Data deduplication and sanitization before processing

Before processing data, it’s essential to ensure that the data is clean and free of duplicates. The remove() method can be used to remove duplicates from a list. For example, in a data processing pipeline, you might want to remove duplicate records from a list of data entries. Here’s an example:

List<DataEntry> dataEntries = new ArrayList<>();
// Assuming dataEntries is populated with data entries

// Remove all duplicate data entries from the list
dataEntries.removeIf(dataEntry -> dataEntries.indexOf(dataEntry) != dataEntries.lastIndexOf(dataEntry));

Common Errors and Debugging

ConcurrentModificationException when removing inside a for-each loop

A ConcurrentModificationException occurs when you try to modify a list (e.g., by removing an element) while iterating over it using a for-each loop. This is because the for-each loop is designed to iterate over the list in its original state, and modifying the list during iteration can lead to unpredictable behavior.

To fix this error, you can use an iterator explicitly and call its remove() method to safely remove elements from the list while iterating. Here’s an example:

List<String> list = new ArrayList<>();
// Assuming list is populated with elements

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    if (element.equals("specificElementToRemove")) {
        iterator.remove();
    }
}

Alternatively, you can use a traditional for loop with an index and remove elements using the remove(int) method. However, be careful when adjusting the index to account for the removed elements.

Difference between remove(int) and remove(Object) in overloaded methods

The remove(int) method removes the element at the specified index, while the remove(Object) method removes the first occurrence of the specified element. If the element is not found in the list, the remove(Object) method does not modify the list and returns false.

To avoid confusion between these methods, ensure you understand the context and the type of parameter you are passing. If you need to remove an element by its index, use remove(int). If you need to remove an element by its value, use remove(Object).

Here is a comparison table to help you understand the differences:

Method Parameter Type Description Returns
remove(int) int Removes the element at the specified index. The element that was removed from the list.
remove(Object) Object Removes the first occurrence of the specified element. true if the list contained the specified element, false otherwise.

Remember to use the correct method based on your requirements to avoid unexpected behavior or errors.

IndexOutOfBoundsException error

An IndexOutOfBoundsException occurs when you try to access or remove an element at an index that is out of the list’s bounds. This can happen if you pass an index that is less than 0 or greater than or equal to the list’s size.

To fix this error, ensure that the index you are using is within the valid range of the list. You can do this by checking the list’s size before attempting to access or remove an element. Here’s an example:

List<String> list = new ArrayList<>();
// Assuming list is populated with elements

int indexToRemove = 5; // Example index
if (indexToRemove >= 0 && indexToRemove < list.size()) {
    list.remove(indexToRemove);
} else {
    System.out.println("Index is out of bounds.");
}

remove() vs removeIf()

The remove() method is used to remove an element from the list based on its index. The removeIf() method is used to remove elements from the list based on a condition.

Here is a comparison table to help you understand the differences:

Method Description Returns Throws
remove(int) Removes the element at the specified index. The element that was removed from the list. IndexOutOfBoundsException if the index is out of range (index < 0 or index >= size()).
remove(Object) Removes the first occurrence of the specified element. true if the list contained the specified element, false otherwise. None
removeIf(Predicate<? super E> filter) Removes all elements of the list that match the given predicate. true if any elements were removed, false otherwise. UnsupportedOperationException if the list implementation does not support this operation.

FAQs

1. What is the difference between remove(int) and remove(Object) in Java?

The remove(int) method removes the element at the specified index, while the remove(Object) method removes the first occurrence of the specified element. Here’s an example:

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

// Remove by index
list.remove(1); // Removes "Banana"
System.out.println(list); // [Apple, Cherry]

// Remove by value
list.remove("Cherry"); // Removes "Cherry"
System.out.println(list); // [Apple]

2. How do I remove all elements from a List in Java?

You can use the clear() method to remove all elements from a list. Here’s an example:

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

list.clear(); // Removes all elements
System.out.println(list); // []

3. Can I use remove() inside a loop?

Yes, you can use remove() inside a loop, but be careful when adjusting the index to account for the removed elements. Here’s an example:

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

for (int i = 0; i < list.size(); i++) {
    if (list.get(i).equals("Banana")) {
        list.remove(i); // Removes "Banana"
        i--; // Adjust index to account for the removed element
    }
}
System.out.println(list); // [Apple, Cherry]

4. How do I avoid ConcurrentModificationException when removing?

To avoid ConcurrentModificationException, use an Iterator to iterate over the list and remove elements. Here’s an example:

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    if (element.equals("Banana")) {
        iterator.remove(); // Removes "Banana"
    }
}
System.out.println(list); // [Apple, Cherry]

5. How do I remove an element by value, not by index?

You can use the remove(Object) method to remove an element by its value. Here’s an example:

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

list.remove("Banana"); // Removes "Banana"
System.out.println(list); // [Apple, Cherry]

6. Why does remove() not work on some lists in Java 9+?

In Java 9+, some lists, such as List.of(), are immutable and do not support the remove() method. Attempting to use remove() on these lists will throw an UnsupportedOperationException. Here’s an example:

List<String> list = List.of("Apple", "Banana", "Cherry");
try {
    list.remove("Banana"); // Throws UnsupportedOperationException
} catch (UnsupportedOperationException e) {
    System.out.println("This list does not support remove operations.");
}

7. What’s the best way to remove elements conditionally?

The best way to remove elements conditionally is to use the removeIf() method, which was introduced in Java 8. Here’s an example:

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

list.removeIf(element -> element.equals("Banana")); // Removes "Banana"
System.out.println(list); // [Apple, Cherry]

Conclusion

In this article, you learned about Java’s List method remove(), which allows you to remove elements from a list by their index or by their value. You also discovered how to use the removeIf() method to conditionally remove elements based on a predicate. Additionally, you were introduced to the concept of immutable lists in Java 9+, which do not support the remove() method. By mastering these techniques, you can effectively manage and manipulate lists in your Java applications.

Recommended Reading:

References:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Pankaj Kumar
Pankaj Kumar
See author profile
Category:
Tutorial
Tags:

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 10, 2020

Thanks for this post…it helps.

- Possible

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 13, 2020

    why gives me a compile error which it tell cannot find the symbol

    - Danuja

      Join the Tech Talk
      Success! Thank you! Please check your email for further details.

      Please complete your information!

      Become a contributor for community

      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

      DigitalOcean Documentation

      Full documentation for every DigitalOcean product.

      Resources for startups and SMBs

      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

      Get our newsletter

      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

      New accounts only. By submitting your email you agree to our Privacy Policy

      The developer cloud

      Scale up as you grow — whether you're running one virtual machine or ten thousand.

      Get started for free

      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

      *This promotional offer applies to new accounts only.