简体   繁体   English

如何使用 subList() 或任何其他方法获取 java.util.List 中的最后一条记录?

[英]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.假设我有一个大小为 100 的元素列表。现在我只想要列表中的第 100 条记录,并且应该从列表中删除 1-99 中的所有记录的其余部分。

I have tried the below piece of code but no change in list size as I see it.我已经尝试了下面的代码,但我看到的列表大小没有变化。
//Output list.size() returns 100 //输出list.size()返回100

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

//Output list.size() returns 100 after subList() called... // 调用 subList() 后输出 list.size() 返回 100...
How can I get just the last record in the java.util.List using subList() or using any other methods available in Java?如何使用 subList() 或使用 Java 中可用的任何其他方法获取 java.util.List 中的最后一条记录?

list.subList returns a new List backed by the original List . list.subList返回一个新的List由最初的支持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. subList.size()将为1. list将保持不变。

If you want to remove all but the last element from the original List , you can write: 如果要删除原始List除最后一个元素之外的所有元素,可以编写:

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

Now the original List will contain just 1 element. 现在原始List只包含1个元素。

ArrayList.subList method returns a sublist of your list without modifying your existing list. ArrayList.subList方法返回列表的子列表,而不修改现有列表。

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. 这适用于任何列表,对ArrayList实现最有效。

You can do it by importing com.google.common.collect.Iterables, but be aware if list is empty it will throw NoSuchElementException .您可以通过导入 com.google.common.collect.Iterables 来做到这一点,但请注意,如果列表为空,它将抛出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您也可以使用流: https ://www.baeldung.com/java-stream-last-element

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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