Remove an element from list Java

In this quick article, well see how to remove the last element of a list in Java.

We can use the remove[int index] method of the List interface, which removes an element at the specified position in the list. To remove the last element, we need to pass the index of the last element, as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Main
{
public static void main[String[] args]
{
List list = new ArrayList[];
list.addAll[Arrays.asList["A", "B", "C", "D", "E"]];
System.out.println["Original list: " + list];// [A, B, C, D, E]
int indexOfLastElement = list.size[] - 1;
list.remove[indexOfLastElement];
System.out.println["Modified list: " + list];// [A, B, C, D]
}
}

DownloadRun Code

Output:

Original list: [A, B, C, D, E]
Modified list: [A, B, C, D]


The remove method is overloaded in the List interface. If all the list elements are distinct, and we know the last element, we can call the remove[Object o] method. It removes the first occurrence of the specified element from the list if present.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Main
{
public static void main[String[] args]
{
List list = new ArrayList[];
list.addAll[Arrays.asList["A", "B", "C", "D", "E"]];
System.out.println["Original list: " + list];// [A, B, C, D, E]
list.remove["E"];
System.out.println["Modified list: " + list];// [A, B, C, D]
}
}

DownloadRun Code

Output:

Original list: [A, B, C, D, E]
Modified list: [A, B, C, D]


Note its preferable to use a Deque instead of a List, which efficiently supports deletion at the end. Following is a simple example demonstrating deletion in Deque:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
class Main
{
public static void main[String[] args]
{
Deque list = new ArrayDeque[];
list.addAll[Arrays.asList["A", "B", "C", "D", "E"]];
System.out.println["Original list: " + list];// [A, B, C, D, E]
list.removeLast[];
System.out.println["Modified list: " + list];// [A, B, C, D]
}
}

DownloadRun Code

Output:

Original list: [A, B, C, D, E]
Modified list: [A, B, C, D]

Thats all about removing the last element of a List in Java.

Video liên quan

Chủ Đề