Java get last element of a collection

前端 未结 10 752
你的背包
你的背包 2020-12-30 18:47

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

相关标签:
10条回答
  • 2020-12-30 19:00

    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)

    0 讨论(0)
  • 2020-12-30 19:00

    If you have Iterable convert to stream and find last element

     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);
    
    0 讨论(0)
  • 2020-12-30 19:10

    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;
    }
    
    0 讨论(0)
  • 2020-12-30 19:11

    Or you can use a for-each loop:

    Collection<X> items = ...;
    X last = null;
    for (X x : items) last = x;
    
    0 讨论(0)
  • 2020-12-30 19:13

    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. This isn't always the case, not all Collections are ordered.

    Object lastElement = null;
    
    for (Iterator collectionItr = c.iterator(); collectionItr.hasNext(); ) {
      lastElement = collectionItr.next();
    }
    
    0 讨论(0)
  • 2020-12-30 19:13

    This should work without converting to List/Array:

    collectionName.stream().reduce((prev, next) -> next).orElse(null)
    
    0 讨论(0)
提交回复
热议问题