Returns an Optional containing the last element in this fluent iterable. If the iterable is empty, Optional.absent() is returned. If the underlying iterable is a List with java.util.RandomAccess support, then this operation is guaranteed to be O(1). <
()
| 538 | |
| 539 | |
| 540 | public final Optional<E> last() { |
| 541 | // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE |
| 542 | |
| 543 | // TODO(kevinb): Support a concurrently modified collection? |
| 544 | if (iterable instanceof List) { |
| 545 | List<E> list = (List<E>) iterable; |
| 546 | if (list.isEmpty()) { |
| 547 | return Optional.absent(); |
| 548 | } |
| 549 | return Optional.of(list.get(list.size() - 1)); |
| 550 | } |
| 551 | Iterator<E> iterator = iterable.iterator(); |
| 552 | if (!iterator.hasNext()) { |
| 553 | return Optional.absent(); |
| 554 | } |
| 555 | |
| 556 | /* |
| 557 | * TODO(kevinb): consider whether this "optimization" is worthwhile. Users with SortedSets tend |
| 558 | * to know they are SortedSets and probably would not call this method. |
| 559 | */ |
| 560 | if (iterable instanceof SortedSet) { |
| 561 | SortedSet<E> sortedSet = (SortedSet<E>) iterable; |
| 562 | return Optional.of(sortedSet.last()); |
| 563 | } |
| 564 | |
| 565 | while (true) { |
| 566 | E current = iterator.next(); |
| 567 | if (!iterator.hasNext()) { |
| 568 | return Optional.of(current); |
| 569 | } |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | /** |
| 574 | * Returns a view of this fluent iterable that skips its first {@code numberToSkip} elements. If |