简体   繁体   English

Java获取集合的最后一个元素

[英]Java get last element of a collection

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.一个解决方案是先toArray(),然后返回数组的最后一个元素。 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. Collection不一定是有序的元素集,因此可能没有“最后一个”元素的概念。 If you want something that's ordered, you can use a SortedSet which has a last() method.如果你想要一些有序的东西,你可以使用具有last()方法的SortedSet Or you can use a List and call mylist.get(mylist.size()-1);或者您可以使用List并调用mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet .如果你真的需要最后一个元素,你应该使用ListSortedSet 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.但是,如果您拥有的只是一个Collection并且您真的,真的,真的需要最后一个元素,则可以使用toArray()或者您可以使用Iterator并迭代到列表的末尾。

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;
}

Iterables.getLast from Google Guava.来自 Google Guava 的Iterables.getLast It has some optimization for List s and SortedSet s too.它也对ListSortedSet进行了一些优化。

It is not very efficient solution, but working one:这不是非常有效的解决方案,但可以工作:

public static <T> T getFirstElement(final Iterable<T> elements) {
    return elements.iterator().next();
}

public static <T> T getLastElement(final Iterable<T> elements) {
    T lastElement = null;

    for (T element : elements) {
        lastElement = element;
    }

    return lastElement;
}

Well one solution could be:那么一种解决方案可能是:

list.get(list.size()-1)

Edit: You have to convert the collection to a list before maybe like this: new ArrayList(coll)编辑:您必须先将集合转换为列表,然后再像这样:new ArrayList(coll)

这应该可以在不转换为列表/数组的情况下工作:

collectionName.stream().reduce((prev, next) -> next).orElse(null)

A reasonable solution would be to use an iterator if you don't know anything about the underlying Collection, but do know that there is a "last" element.如果您对底层 Collection 一无所知,但知道有一个“最后一个”元素,那么一个合理的解决方案是使用迭代器。 This isn't always the case, not all Collections are ordered.情况并非总是如此,并非所有 Collections 都是有序的。

Object lastElement = null;

for (Iterator collectionItr = c.iterator(); collectionItr.hasNext(); ) {
  lastElement = collectionItr.next();
}

Or you can use a for-each loop:或者您可以使用 for-each 循环:

Collection<X> items = ...;
X last = null;
for (X x : items) last = x;

If you have Iterable convert to stream and find last element如果您有 Iterable 转换为流并找到最后一个元素

 Iterator<String> sourceIterator = Arrays.asList("one", "two", "three").iterator();

 Iterable<String> iterable = () -> sourceIterator;


 String last = StreamSupport.stream(iterable.spliterator(), false).reduce((first, second) -> second).orElse(null);

There isn't a last() or first() method in a Collection interface. Collection 接口中没有last()first()方法。 For getting the last method, you can either do get(size() - 1) on a List or reverse the List and do get(0) .要获得最后一个方法,您可以在 List 上执行get(size() - 1)或反转 List 并执行get(0) I don't see a need to have last() method in any Collection API unless you are dealing with Stacks or Queues除非您正在处理StacksQueues否则我认为不需要在任何集合 API 中使用last()方法

To avoid some of the problems mentioned above (not robust for nulls etc etc), to get first and last element in a list an approach could be 为了避免上面提到的一些问题(对于null等不稳健),要获取列表中的第一个和最后一个元素,可以采用以下方法:

import java.util.List;

public static final <A> A getLastElement(List<A> list) {
    return list != null ? getElement(list, list.size() - 1) : null;
}

public static final <A> A getFirstElement(List<A> list) {
    return list != null ? getElement(list, 0) : null;
}   

private static final <A> A getElement(List<A> list, int pointer) {
    A res = null;
    if (list.size() > 0) {
        res = list.get(pointer);            
    }
    return res;
}

The convention adopted is that the first/last element of an empty list is null... 采用的惯例是,空列表的第一个/最后一个元素为null ...

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

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