MCPcopy
hub / github.com/google/guava / last

Method last

guava/src/com/google/common/collect/FluentIterable.java:529–562  ·  view source on GitHub ↗

Returns an {@link Optional} containing the last element in this fluent iterable. If the iterable is empty, {@code Optional.absent()} is returned. If the underlying {@code iterable} is a {@link List} with {@link java.util.RandomAccess} support, then this operation is guaranteed to be {@code O(1)}. <

()

Source from the content-addressed store, hash-verified

527 * Iterables#getLast} instead.
528 */
529 @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
530 public final Optional<@NonNull E> last() {
531 // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE
532
533 // TODO(kevinb): Support a concurrently modified collection?
534 Iterable<E> iterable = getDelegate();
535 if (iterable instanceof List) {
536 List<E> list = (List<E>) iterable;
537 if (list.isEmpty()) {
538 return Optional.absent();
539 }
540 return Optional.of(list.get(list.size() - 1));
541 }
542 Iterator<E> iterator = iterable.iterator();
543 if (!iterator.hasNext()) {
544 return Optional.absent();
545 }
546
547 /*
548 * TODO(kevinb): consider whether this "optimization" is worthwhile. Users with SortedSets tend
549 * to know they are SortedSets and probably would not call this method.
550 */
551 if (iterable instanceof SortedSet) {
552 SortedSet<E> sortedSet = (SortedSet<E>) iterable;
553 return Optional.of(sortedSet.last());
554 }
555
556 while (true) {
557 E current = iterator.next();
558 if (!iterator.hasNext()) {
559 return Optional.of(current);
560 }
561 }
562 }
563
564 /**
565 * Returns a view of this fluent iterable that skips its first {@code numberToSkip} elements. If

Callers

nothing calls this directly

Calls 9

getDelegateMethod · 0.95
absentMethod · 0.95
ofMethod · 0.95
isEmptyMethod · 0.65
getMethod · 0.65
sizeMethod · 0.65
iteratorMethod · 0.65
nextMethod · 0.65
hasNextMethod · 0.45

Tested by

no test coverage detected