简体   繁体   中英

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

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?

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.

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

So you need to do;

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

To get just last record without changing list you could use:

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

this will work for any list, most effective for ArrayList implementation.

You can do it by importing com.google.common.collect.Iterables, but be aware if list is empty it will throw NoSuchElementException .

public MODEL getLastEntry(List<MODEL> list) {
   return Iterables.getLast(list);
}

You can also use stream for it: https://www.baeldung.com/java-stream-last-element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM