当前位置:   article > 正文

java list获取最后一个元素的值,Java获取集合的最后一个元素

java11获取list最后一个元素

I have a collection, I want to get the last element of the collection. What's the most straighforward and fast way to do so?

One solution is to first toArray(), and then return the last element of the array. Is there any other better ones?

解决方案

A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray or you could use an Iterator and iterate to the end of the list. For example:

public Object getLastElement(final Collection c) {

final Iterator itr = c.iterator();

Object lastElement = itr.next();

while(itr.hasNext()) {

lastElement=itr.next();

}

return lastElement;

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/77394
推荐阅读
相关标签
  

闽ICP备14008679号