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.
remove()
MethodsThere are two remove()
methods to remove elements from the List.
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.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.
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.
IndexOutOfBoundsException
with remove(int index)
MethodThis 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
:
OutputException 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
.
remove()
UnsupportedOperationException
ExampleThe 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
:
OutputException 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")
.
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
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));
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);
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));
ConcurrentModificationException
when removing inside a for-each loopA 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.
remove(int)
and remove(Object)
in overloaded methodsThe 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
errorAn 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. |
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]
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); // []
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]
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]
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]
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.");
}
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]
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.
Thanks for this post…it helps.
- Possible
why gives me a compile error which it tell cannot find the symbol
- Danuja