Remove last element from a List in Java
In this quick article, we’ll 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<String> 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] } } |
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<String> 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] } } |
Output:
Original list: [A, B, C, D, E]
Modified list: [A, B, C, D]
Note it’s 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<String> 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] } } |
Output:
Original list: [A, B, C, D, E]
Modified list: [A, B, C, D]
That’s all about removing the last element of a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)