How to remove element from arraylist in java

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn how to remove element from arraylist in java.

how to remove element from arraylist in java

How to remove element from arraylist in java

In ArrayList we have two overloaded remove methods. One is, remove (int index) and the example is as shown and the other is explained below.

import java.util.ArrayList;
import java.util.List;
public class RemoveElementDemo
{
public static void main(String[] args)
{
List li = new ArrayList();
li.add(63);
li.add(86);
li.add(82);
li.add(66);
li.add(95);
li.remove(1); // removes element at index 1, that is, 86
li.remove(1); // now element 82 is removed
System.out.println("After removing elements from ArrayList : " + li);
}
}

Output:

After removing elements from ArrayList : [63, 66, 95]

So remove (int index) method accepts index of object to be removed. As you can see the output, the passed parameter is considered as index.

Also read – Remove Element From Array Java

Now we will see how to remove elements by value and passed parameter is considered as index,

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

public class RemoveElementExample
{
public static void main(String[] args)
{
List li = new ArrayList();
li.add(63);
li.add(86);
li.add(82);
li.add(66);
li.add(95);
li.remove(new Integer(1)); // removes element at index 1, that is, 86
li.remove(new Integer(2)); // now element 82 is removed
System.out.println("After removing elements from ArrayList : " + li);
}
}

Output:

After removing elements from ArrayList : [63, 86, 82]

NOTE:

ArrayList.remove() is not recommended to use while iterating over elements. Because it may lead to ConcurrentModificationException. Instead use Iterator.remove() method

Remove an element from collection using java Iterator

Here we will learn how to remove an element from collection using Iterator object,

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

public class IteratorRemoveDemo
{
public static void main(String[] args)
{
List li = new ArrayList();
li.add(10);
li.add(20);
li.add(30);
li.add(07);
li.add(06);
Iterator ite = li.iterator();
while(ite.hasNext())
{
int a = (Integer)ite.next();
if(a < 10)
ite.remove();
}
System.out.println("After removing elements from ArrayList : " + li);
}
}

Output:

After removing elements from ArrayList : [10, 20, 30]

Related Posts