Say I have a list of elements whose size is 100. Now I only want the 100th record in the list and the rest of all records from 1-99 should be removed from the list.
I have tried the below piece of code but no change in list size as I see it.
//Output list.size() returns 100
list.subList(list.size()-1, list.size());
//Output list.size() returns 100 after subList() called...
How can I get just the last record in the java.util.List using subList() or using any other methods available in Java?
Get the ArrayList with elements. Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.
contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
Java List add() This method is used to add elements to the list. There are two methods to add elements to the list. add(E e): appends the element at the end of the list.
The subList() method of java. util. ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.)
list.subList
returns a new List
backed by the original List
.
You need to store the returned list in a variable in order to use it:
List<String> subList = list.subList(list.size()-1, list.size());
subList.size()
will be 1. list
will remain unchanged.
If you want to remove all but the last element from the original List
, you can write:
list.subList(0, list.size()-1).clear();
Now the original List
will contain just 1 element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With