Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I just get the last record in the java.util.List using subList() or any other method?

Tags:

java

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?

like image 965
mannedear Avatar asked Dec 06 '17 12:12

mannedear


People also ask

How do you call the last element of a List 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.

How do you check if elements of a List is present in another List in Java?

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.

Which method of List is used to add element at the end?

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.

How do you retrieve a portion of an ArrayList?

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.)


1 Answers

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.

like image 57
Eran Avatar answered Sep 28 '22 11:09

Eran