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

Let's say I have a list of elements of size 100. Now I want only the 100th entry in the list, and the remaining entries from 1-99 should be removed from the list.

I tried the following code snippet but did not resize the list as I see it.
// Exit list.size () returns 100

list.subList(list.size()-1, list.size()); 

// The output of list.size () returns 100 after calling subList () ...
How can I get only the last entry in java.util.List using subList () or using any other methods available in Java?

+5
source share
3 answers

The ArrayList.subList method returns a list of your list without modifying the existing list.

So you need to do;

 list = list.subList(list.size()-1, list.size()); 
+3
source

list.subList returns a new List supported 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 equal to 1. List will remain unchanged.

If you want to remove everything except the last item from the original List , you can write:

 list.subList(0, list.size()-1).clear(); 

Now the original List will contain only one element.

+7
source

To get only the last entry without changing the list, you can use:

 element = list.get(list.size()-1); 

this will work for any list that is most effective for implementing an ArrayList .

+2
source

Source: https://habr.com/ru/post/1273887/


All Articles