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). <
()
| 503 | * {@link Iterables#getLast} instead. |
| 504 | */ |
| 505 | public final Optional<E> last() { |
| 506 | // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE |
| 507 | |
| 508 | // TODO(kevinb): Support a concurrently modified collection? |
| 509 | if (iterable instanceof List) { |
| 510 | List<E> list = (List<E>) iterable; |
| 511 | if (list.isEmpty()) { |
| 512 | return Optional.absent(); |
| 513 | } |
| 514 | return Optional.of(list.get(list.size() - 1)); |
| 515 | } |
| 516 | Iterator<E> iterator = iterable.iterator(); |
| 517 | if (!iterator.hasNext()) { |
| 518 | return Optional.absent(); |
| 519 | } |
| 520 | |
| 521 | /* |
| 522 | * TODO(kevinb): consider whether this "optimization" is worthwhile. Users with SortedSets tend |
| 523 | * to know they are SortedSets and probably would not call this method. |
| 524 | */ |
| 525 | if (iterable instanceof SortedSet) { |
| 526 | SortedSet<E> sortedSet = (SortedSet<E>) iterable; |
| 527 | return Optional.of(sortedSet.last()); |
| 528 | } |
| 529 | |
| 530 | while (true) { |
| 531 | E current = iterator.next(); |
| 532 | if (!iterator.hasNext()) { |
| 533 | return Optional.of(current); |
| 534 | } |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | /** |
| 539 | * Returns a view of this fluent iterable that skips its first {@code numberToSkip} elements. If |