try this

list.removeAll(Arrays.asList(2));

it will remove all elements with value = 2

you can also use this

list.remove(Integer.valueOf(2));

but it will remove only first occurence of 2

list.remove(2) does not work because it matches List.remove(int i) which removes element with the specified index

Answer from Evgeniy Dorofeev on Stack Overflow
🌐
W3Schools
w3schools.com › java › ref_arraylist_remove.asp
Java ArrayList remove() Method
If the list contains integers and you want to delete an integer based on its value you will need to pass an Integer object. See More Examples below for an example. ... T refers to the data type of items in the list.
Discussions

Processing 1.0 - Processing Discourse - removing elements of an arrayList
Processing is an electronic sketchbook for developing ideas. It is a context for learning fundamentals of computer programming within the context of the electronic arts. More on forum.processing.org
🌐 forum.processing.org
June 4, 2010
(Java) Can't remove element from List/ArrayList, always gives NullPointerException or ConcurrentModificationException.
You add every line to the list, but the last line of the file will always return null. You correctly end the loop at that point, but you still add null to the list. That's what is giving those nullpointer exceptions More on reddit.com
🌐 r/AskProgramming
6
1
March 22, 2020
java - C# is fantastic, if only List 'd respect Remove&Return - Software Engineering Stack Exchange
In the domain of system-modeling (e, systemVerilog, matlab, phyton), lists are obsoleting arrays, stacks and queues(*) altogether. Other domains that use python, perl and ruby have that same mindse... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
January 31, 2020
How does an ArrayList remove an element from an array?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
6
10
March 15, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › java › removing-element-from-the-specified-index-in-java-arraylist
Removing Element from the Specified Index in Java ArrayList - GeeksforGeeks
March 31, 2023 - The remove(int index) method present in java.util.ArrayList class removes the element at the specified position in this list and shifts any subsequent elements to the left (i.e.
🌐
Medium
medium.com › @AlexanderObregon › removing-specific-numbers-from-a-java-list-d369645d860a
Removing Specific Numbers from a Java List | Medium
August 13, 2025 - Separating the traversal list from the one being modified means there’s no interference with the iterator’s integrity. While it uses more memory for the copy, it completely avoids concurrent modification problems. Starting with Java 8, removeIf became available to any class implementing Collection, which includes List. This method accepts a predicate, which is a boolean-returning function, to decide whether each element should be removed. removeIf removes elements safely during traversal. In ArrayList, it compacts the backing array in place rather than relying on the public Iterator, so you don’t have to manage indexes or create copies.
🌐
Processing Forum
forum.processing.org › beta › num_1275642093.html
Processing 1.0 - Processing Discourse - removing elements of an arrayList
June 4, 2010 - Index › Programming Questions & Help › Syntax Questions › removing elements of an arrayList · Processing was initiated by Ben Fry and Casey Reas.
🌐
Vaia
vaia.com › all textbooks › computer science › starting out with java: from control structures through objects › chapter 7 › problem 27
How do you remove an item from an ArrayList object? - Vaia
In this case, removing an integer value, there will be no issues because Java's Integer class already implements the equals() method properly. Now you know how to remove an item from an ArrayList object by using either the remove() method with an ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-list-remove-methods-arraylist-remove
How To Use remove() Methods for Java List and ArrayList | DigitalOcean
September 9, 2025 - 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));
Find elsewhere
🌐
Coderanch
coderanch.com › t › 604659 › java › Removing-Integer-values-ArrayList
Removing Integer values from ArrayList (Beginning Java forum at Coderanch)
February 11, 2013 - Can anyone please help me out in this regard, please? Code snippet is something like How to remove 10 and 2 in the above code snippet?? Thanks for help in advance Regards, Krishna ... Hi Krishna, You can remove the integers from arraylist by using remove method of iterator interface.
🌐
Programiz
programiz.com › java-programming › library › arraylist › remove
Java ArrayList remove()
Notice the line, randomNumbers.remove(Integer.valueOf(13)) Here, Integer.valueOf() - Converts the int value 13 to an Integer object. It is because the remove() method only takes objects as its arguments. To learn more, visit Java Primitive Types to Wrapper Objects.
🌐
CodeGym
codegym.cc › java blog › java collections › how to remove an element from arraylist in java?
How to remove an element from ArrayList in Java | CodeGym
December 10, 2024 - The iterator is smarter than it may appear: remove() removes the last element returned by the iterator. As you can see, it did just what we wanted it to do :) In principle, this is everything you need to know about removing elements from an ArrayList. Well, almost everything. In the next lesson, we'll look inside this class, and see what happens there during various method calls :) Until then! ... Volodymyr is one of those who learned Java development thanks to the CodeGym course, and after studying, got a job in our company.
🌐
GeeksforGeeks
geeksforgeeks.org › java › remove-first-element-from-arraylist-in-java
Remove first element from ArrayList in Java - GeeksforGeeks
July 12, 2025 - If the ArrayList does not contain duplicates, we can simply pass the first element value as an object to be deleted to the remove() method, and it will delete that value. Note: Incase the ArrayList contains duplicates, it will delete the first ...
🌐
Reddit
reddit.com › r/askprogramming › (java) can't remove element from list/arraylist, always gives nullpointerexception or concurrentmodificationexception.
r/AskProgramming on Reddit: (Java) Can't remove element from List/ArrayList, always gives NullPointerException or ConcurrentModificationException.
March 22, 2020 -

I have an ArrayList that has some elements that should be removed, or not even added in the first place, but it always throws on of the two exceptions mentioned in the title.

So I have the following arraylist:

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

I add elements to it like this (this is all working so far, println prints every single element perfectly):

    BufferedReader reader;
    reader = new BufferedReader(new StringReader(extractor.getText()));
   String line = reader.readLine();
    while (line != null) {
        line = reader.readLine();
        doc.add(line);
    }
    reader.close();

But I have some repeating elements that I want to remove, these all contain ".lap".

So I try to remove it in a for-each loop:

    for (String s : doc) {
        if (s.contains(".lap")) {
            doc.remove(s);
        }
    }

Which give me a ConcurrentModificationException.

I looked into it and on StackOverflow they said an Iterator should be used, so I did the following:

    Iterator<String> i = doc.iterator();
    while (i.hasNext()) {
        String s = i.next();
       if (s.contains(".lap")) {
            i.remove();
        }
    }

This one throws a NullPointerException.

So I tried not removing elements, but skipping them all together when reading from the input, so I modified the first block of code like this:

    String line = reader.readLine();
    while (line != null) {
        line = reader.readLine();
        if (!line.contains(".lap")) {
            doc.add(line);
        }
    }
    reader.close();

This one also throws a NullPointerException.

So how should I remove (or not even add in the first place) some specific lines/elements in an ArrayList? I even looked for an answer on the 2nd Google page and still nothing.

Top answer
1 of 1
7

Typically, people remove things from lists already knowing what those things are, as that knowledge is why they want to remove the item in the first place. By contrast, people don't usually want to remove specific known items from a stack/queue, but rather retrieve the first/last element.

Probably relevant factors:

  1. Consistency with List<T>.Remove(T).
    A List<T> has a .Remove(T) method that returns a bool indicating if the removal was successful. So, for consistency, we'd expect .RemoveAt(int) to do the same. Except .RemoveAt(int) can't really fail (unless the index is out-of-range, in which case it throws an exception instead), so it just returns void instead.

  2. Removing an item from a list doesn't imply retrieval.
    Queues/stacks are all about specific process models in which things are queued/stacked and then dequeued/popped for processing, such that removal and retrieval are conceptually linked together. By contrast, lists don't inherently imply such an operational model.

  3. Retrieval is readily available for when someone would want it.
    If a caller would want to retrieve the item at the index before removing it, then they can just specify that with list[index].

It's worth noting that a hypothetical ConcurrentList<T> would've probably implemented

partial public class ConcurrentList<T>
{
    public bool TryRemoveAt(
                int targetIndex
            ,   out T successfullyRemovedItem
        )
    { /* ... */ }
}

, analogous to a similar .TryRemove(T_Key, out T_Value) for ConcurrentDictionary<T_Key, T_Value>'s.

Finally, the main use-case of List.RemoveAt() is probably something like:

for (int i=0; i < list.count; ++i)
{
    if (someConditionalCheck(list[i]))
    {
        list.RemoveAt(i);
        break;
    }
}

, where it's important to note that break;, since if the loop continues without breaking after removal, then it'll skip an element. This could be fixed by also manually decrementing i, e.g. --i instead of break;, but at that point the code's getting pretty twisted. Plus it'd be poor form to try something like this without a break;, anyway, as list-removal is O(n), making it a poor choice of data structure to use if someone expects to loop over multiple removals as that could be O(n2).

🌐
Dotnetcodr
dotnetcodr.com › 2015 › 02 › 14 › conditionally-remove-elements-from-a-list-in-java-8
Conditionally remove elements from a List in Java 8 | Exercises in .NET with Andras Nemes
August 29, 2015 - In that case the method will throw an UnsupportedOperationException in case an attempt is made to remove a matching element. The ArrayList is one such collection: Collection<String> asList = Arrays.asList("hello", "my", "dear", "world"); asList.removeIf(s -> s.contains("ll")); This will throw an exception unfortunately as the Array.asList method returns an ArrayList of type java.util.Arrays.ArrayList (which is read only and fixed size) and not the classic java.util.ArrayList (resizable and item-removable) – based on a comment by Juanito below.
🌐
Coderolls
coderolls.com › remove-element-from-arraylist
How To Remove An Element From An ArrayList? | Coderolls
December 2, 2021 - We will see a Java program to remove an element from the ArrayList by passing its index as an argument to the remove(int index) method.
🌐
Codegrepper
codegrepper.com › code-examples › java › remove+element+from+arraylist+java
remove item from arraylist in java - Code Examples & Solutions
//Create the ArrayList List al = new ArrayList (); //Add the items al.add(10); al.add(18); //Remove item(1 = 2and item in list) al.remove(1);