001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.collect;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.GwtCompatible;
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.base.Function;
022import com.google.common.base.Joiner;
023import com.google.common.base.Optional;
024import com.google.common.base.Predicate;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.InlineMe;
027import java.util.Arrays;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.Comparator;
031import java.util.Iterator;
032import java.util.List;
033import java.util.SortedSet;
034import java.util.stream.Stream;
035import javax.annotation.CheckForNull;
036import org.checkerframework.checker.nullness.qual.NonNull;
037import org.checkerframework.checker.nullness.qual.Nullable;
038
039/**
040 * A discouraged (but not deprecated) precursor to Java's superior {@link Stream} library.
041 *
042 * <p>The following types of methods are provided:
043 *
044 * <ul>
045 *   <li>chaining methods which return a new {@code FluentIterable} based in some way on the
046 *       contents of the current one (for example {@link #transform})
047 *   <li>element extraction methods which facilitate the retrieval of certain elements (for example
048 *       {@link #last})
049 *   <li>query methods which answer questions about the {@code FluentIterable}'s contents (for
050 *       example {@link #anyMatch})
051 *   <li>conversion methods which copy the {@code FluentIterable}'s contents into a new collection
052 *       or array (for example {@link #toList})
053 * </ul>
054 *
055 * <p>Several lesser-used features are currently available only as static methods on the {@link
056 * Iterables} class.
057 *
058 * <p><a id="streams"></a>
059 *
060 * <h3>Comparison to streams</h3>
061 *
062 * <p>{@link Stream} is similar to this class, but generally more powerful, and certainly more
063 * standard. Key differences include:
064 *
065 * <ul>
066 *   <li>A stream is <i>single-use</i>; it becomes invalid as soon as any "terminal operation" such
067 *       as {@code findFirst()} or {@code iterator()} is invoked. (Even though {@code Stream}
068 *       contains all the right method <i>signatures</i> to implement {@link Iterable}, it does not
069 *       actually do so, to avoid implying repeat-iterability.) {@code FluentIterable}, on the other
070 *       hand, is multiple-use, and does implement {@link Iterable}.
071 *   <li>Streams offer many features not found here, including {@code min/max}, {@code distinct},
072 *       {@code reduce}, {@code sorted}, the very powerful {@code collect}, and built-in support for
073 *       parallelizing stream operations.
074 *   <li>{@code FluentIterable} contains several features not available on {@code Stream}, which are
075 *       noted in the method descriptions below.
076 *   <li>Streams include primitive-specialized variants such as {@code IntStream}, the use of which
077 *       is strongly recommended.
078 *   <li>Streams are standard Java, not requiring a third-party dependency.
079 * </ul>
080 *
081 * <h3>Example</h3>
082 *
083 * <p>Here is an example that accepts a list from a database call, filters it based on a predicate,
084 * transforms it by invoking {@code toString()} on each element, and returns the first 10 elements
085 * as a {@code List}:
086 *
087 * <pre>{@code
088 * ImmutableList<String> results =
089 *     FluentIterable.from(database.getClientList())
090 *         .filter(Client::isActiveInLastMonth)
091 *         .transform(Object::toString)
092 *         .limit(10)
093 *         .toList();
094 * }</pre>
095 *
096 * The approximate stream equivalent is:
097 *
098 * <pre>{@code
099 * List<String> results =
100 *     database.getClientList()
101 *         .stream()
102 *         .filter(Client::isActiveInLastMonth)
103 *         .map(Object::toString)
104 *         .limit(10)
105 *         .collect(Collectors.toList());
106 * }</pre>
107 *
108 * @author Marcin Mikosik
109 * @since 12.0
110 */
111@GwtCompatible(emulated = true)
112@ElementTypesAreNonnullByDefault
113public abstract class FluentIterable<E extends @Nullable Object> implements Iterable<E> {
114  // We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof
115  // checks on the _original_ iterable when FluentIterable.from is used.
116  // To avoid a self retain cycle under j2objc, we store Optional.absent() instead of
117  // Optional.of(this). To access the delegate iterable, call #getDelegate(), which converts to
118  // absent() back to 'this'.
119  private final Optional<Iterable<E>> iterableDelegate;
120
121  /** Constructor for use by subclasses. */
122  protected FluentIterable() {
123    this.iterableDelegate = Optional.absent();
124  }
125
126  FluentIterable(Iterable<E> iterable) {
127    this.iterableDelegate = Optional.of(iterable);
128  }
129
130  private Iterable<E> getDelegate() {
131    return iterableDelegate.or(this);
132  }
133
134  /**
135   * Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} itself if it is
136   * already a {@code FluentIterable}.
137   *
138   * <p><b>{@code Stream} equivalent:</b> {@link Collection#stream} if {@code iterable} is a {@link
139   * Collection}; {@link Streams#stream(Iterable)} otherwise.
140   */
141  public static <E extends @Nullable Object> FluentIterable<E> from(final Iterable<E> iterable) {
142    return (iterable instanceof FluentIterable)
143        ? (FluentIterable<E>) iterable
144        : new FluentIterable<E>(iterable) {
145          @Override
146          public Iterator<E> iterator() {
147            return iterable.iterator();
148          }
149        };
150  }
151
152  /**
153   * Returns a fluent iterable containing {@code elements} in the specified order.
154   *
155   * <p>The returned iterable is an unmodifiable view of the input array.
156   *
157   * <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#of(Object[])
158   * Stream.of(T...)}.
159   *
160   * @since 20.0 (since 18.0 as an overload of {@code of})
161   */
162  public static <E extends @Nullable Object> FluentIterable<E> from(E[] elements) {
163    return from(Arrays.asList(elements));
164  }
165
166  /**
167   * Construct a fluent iterable from another fluent iterable. This is obviously never necessary,
168   * but is intended to help call out cases where one migration from {@code Iterable} to {@code
169   * FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}.
170   *
171   * @deprecated instances of {@code FluentIterable} don't need to be converted to {@code
172   *     FluentIterable}
173   */
174  @Deprecated
175  @InlineMe(
176      replacement = "checkNotNull(iterable)",
177      staticImports = {"com.google.common.base.Preconditions.checkNotNull"})
178  public static <E extends @Nullable Object> FluentIterable<E> from(FluentIterable<E> iterable) {
179    return checkNotNull(iterable);
180  }
181
182  /**
183   * Returns a fluent iterable that combines two iterables. The returned iterable has an iterator
184   * that traverses the elements in {@code a}, followed by the elements in {@code b}. The source
185   * iterators are not polled until necessary.
186   *
187   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
188   * iterator supports it.
189   *
190   * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}.
191   *
192   * @since 20.0
193   */
194  public static <T extends @Nullable Object> FluentIterable<T> concat(
195      Iterable<? extends T> a, Iterable<? extends T> b) {
196    return concatNoDefensiveCopy(a, b);
197  }
198
199  /**
200   * Returns a fluent iterable that combines three iterables. The returned iterable has an iterator
201   * that traverses the elements in {@code a}, followed by the elements in {@code b}, followed by
202   * the elements in {@code c}. The source iterators are not polled until necessary.
203   *
204   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
205   * iterator supports it.
206   *
207   * <p><b>{@code Stream} equivalent:</b> use nested calls to {@link Stream#concat}, or see the
208   * advice in {@link #concat(Iterable...)}.
209   *
210   * @since 20.0
211   */
212  public static <T extends @Nullable Object> FluentIterable<T> concat(
213      Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) {
214    return concatNoDefensiveCopy(a, b, c);
215  }
216
217  /**
218   * Returns a fluent iterable that combines four iterables. The returned iterable has an iterator
219   * that traverses the elements in {@code a}, followed by the elements in {@code b}, followed by
220   * the elements in {@code c}, followed by the elements in {@code d}. The source iterators are not
221   * polled until necessary.
222   *
223   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
224   * iterator supports it.
225   *
226   * <p><b>{@code Stream} equivalent:</b> use nested calls to {@link Stream#concat}, or see the
227   * advice in {@link #concat(Iterable...)}.
228   *
229   * @since 20.0
230   */
231  public static <T extends @Nullable Object> FluentIterable<T> concat(
232      Iterable<? extends T> a,
233      Iterable<? extends T> b,
234      Iterable<? extends T> c,
235      Iterable<? extends T> d) {
236    return concatNoDefensiveCopy(a, b, c, d);
237  }
238
239  /**
240   * Returns a fluent iterable that combines several iterables. The returned iterable has an
241   * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators
242   * are not polled until necessary.
243   *
244   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
245   * iterator supports it.
246   *
247   * <p><b>{@code Stream} equivalent:</b> to concatenate an arbitrary number of streams, use {@code
248   * Stream.of(stream1, stream2, ...).flatMap(s -> s)}. If the sources are iterables, use {@code
249   * Stream.of(iter1, iter2, ...).flatMap(Streams::stream)}.
250   *
251   * @throws NullPointerException if any of the provided iterables is {@code null}
252   * @since 20.0
253   */
254  public static <T extends @Nullable Object> FluentIterable<T> concat(
255      Iterable<? extends T>... inputs) {
256    return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length));
257  }
258
259  /**
260   * Returns a fluent iterable that combines several iterables. The returned iterable has an
261   * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators
262   * are not polled until necessary.
263   *
264   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
265   * iterator supports it. The methods of the returned iterable may throw {@code
266   * NullPointerException} if any of the input iterators is {@code null}.
267   *
268   * <p><b>{@code Stream} equivalent:</b> {@code streamOfStreams.flatMap(s -> s)} or {@code
269   * streamOfIterables.flatMap(Streams::stream)}. (See {@link Streams#stream}.)
270   *
271   * @since 20.0
272   */
273  public static <T extends @Nullable Object> FluentIterable<T> concat(
274      final Iterable<? extends Iterable<? extends T>> inputs) {
275    checkNotNull(inputs);
276    return new FluentIterable<T>() {
277      @Override
278      public Iterator<T> iterator() {
279        return Iterators.concat(Iterators.transform(inputs.iterator(), Iterable::iterator));
280      }
281    };
282  }
283
284  /** Concatenates a varargs array of iterables without making a defensive copy of the array. */
285  private static <T extends @Nullable Object> FluentIterable<T> concatNoDefensiveCopy(
286      final Iterable<? extends T>... inputs) {
287    for (Iterable<? extends T> input : inputs) {
288      checkNotNull(input);
289    }
290    return new FluentIterable<T>() {
291      @Override
292      public Iterator<T> iterator() {
293        return Iterators.concat(
294            /* lazily generate the iterators on each input only as needed */
295            new AbstractIndexedListIterator<Iterator<? extends T>>(inputs.length) {
296              @Override
297              public Iterator<? extends T> get(int i) {
298                return inputs[i].iterator();
299              }
300            });
301      }
302    };
303  }
304
305  /**
306   * Returns a fluent iterable containing no elements.
307   *
308   * <p><b>{@code Stream} equivalent:</b> {@link Stream#empty}.
309   *
310   * @since 20.0
311   */
312  public static <E extends @Nullable Object> FluentIterable<E> of() {
313    return FluentIterable.from(Collections.<E>emptyList());
314  }
315
316  /**
317   * Returns a fluent iterable containing the specified elements in order.
318   *
319   * <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#of(Object[])
320   * Stream.of(T...)}.
321   *
322   * @since 20.0
323   */
324  public static <E extends @Nullable Object> FluentIterable<E> of(
325      @ParametricNullness E element, E... elements) {
326    return from(Lists.asList(element, elements));
327  }
328
329  /**
330   * Returns a string representation of this fluent iterable, with the format {@code [e1, e2, ...,
331   * en]}.
332   *
333   * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.joining(", ", "[", "]"))}
334   * or (less efficiently) {@code stream.collect(Collectors.toList()).toString()}.
335   */
336  @Override
337  public String toString() {
338    return Iterables.toString(getDelegate());
339  }
340
341  /**
342   * Returns the number of elements in this fluent iterable.
343   *
344   * <p><b>{@code Stream} equivalent:</b> {@link Stream#count}.
345   */
346  public final int size() {
347    return Iterables.size(getDelegate());
348  }
349
350  /**
351   * Returns {@code true} if this fluent iterable contains any object for which {@code
352   * equals(target)} is true.
353   *
354   * <p><b>{@code Stream} equivalent:</b> {@code stream.anyMatch(Predicate.isEqual(target))}.
355   */
356  public final boolean contains(@CheckForNull Object target) {
357    return Iterables.contains(getDelegate(), target);
358  }
359
360  /**
361   * Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of this
362   * fluent iterable.
363   *
364   * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After {@code
365   * remove()} is called, subsequent cycles omit the removed element, which is no longer in this
366   * fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until this fluent
367   * iterable is empty.
368   *
369   * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You
370   * should use an explicit {@code break} or be certain that you will eventually remove all the
371   * elements.
372   *
373   * <p><b>{@code Stream} equivalent:</b> if the source iterable has only a single element {@code
374   * e}, use {@code Stream.generate(() -> e)}. Otherwise, collect your stream into a collection and
375   * use {@code Stream.generate(() -> collection).flatMap(Collection::stream)}.
376   */
377  public final FluentIterable<E> cycle() {
378    return from(Iterables.cycle(getDelegate()));
379  }
380
381  /**
382   * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable,
383   * followed by those of {@code other}. The iterators are not polled until necessary.
384   *
385   * <p>The returned iterable's {@code Iterator} supports {@code remove()} when the corresponding
386   * {@code Iterator} supports it.
387   *
388   * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}.
389   *
390   * @since 18.0
391   */
392  public final FluentIterable<E> append(Iterable<? extends E> other) {
393    return FluentIterable.concat(getDelegate(), other);
394  }
395
396  /**
397   * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable,
398   * followed by {@code elements}.
399   *
400   * <p><b>{@code Stream} equivalent:</b> {@code Stream.concat(thisStream, Stream.of(elements))}.
401   *
402   * @since 18.0
403   */
404  public final FluentIterable<E> append(E... elements) {
405    return FluentIterable.concat(getDelegate(), Arrays.asList(elements));
406  }
407
408  /**
409   * Returns the elements from this fluent iterable that satisfy a predicate. The resulting fluent
410   * iterable's iterator does not support {@code remove()}.
411   *
412   * <p><b>{@code Stream} equivalent:</b> {@link Stream#filter} (same).
413   */
414  public final FluentIterable<E> filter(Predicate<? super E> predicate) {
415    return from(Iterables.filter(getDelegate(), predicate));
416  }
417
418  /**
419   * Returns the elements from this fluent iterable that are instances of class {@code type}.
420   *
421   * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(type::isInstance).map(type::cast)}.
422   * This does perform a little more work than necessary, so another option is to insert an
423   * unchecked cast at some later point:
424   *
425   * <pre>
426   * {@code @SuppressWarnings("unchecked") // safe because of ::isInstance check
427   * ImmutableList<NewType> result =
428   *     (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());}
429   * </pre>
430   */
431  @GwtIncompatible // Class.isInstance
432  public final <T> FluentIterable<T> filter(Class<T> type) {
433    return from(Iterables.filter(getDelegate(), type));
434  }
435
436  /**
437   * Returns {@code true} if any element in this fluent iterable satisfies the predicate.
438   *
439   * <p><b>{@code Stream} equivalent:</b> {@link Stream#anyMatch} (same).
440   */
441  public final boolean anyMatch(Predicate<? super E> predicate) {
442    return Iterables.any(getDelegate(), predicate);
443  }
444
445  /**
446   * Returns {@code true} if every element in this fluent iterable satisfies the predicate. If this
447   * fluent iterable is empty, {@code true} is returned.
448   *
449   * <p><b>{@code Stream} equivalent:</b> {@link Stream#allMatch} (same).
450   */
451  public final boolean allMatch(Predicate<? super E> predicate) {
452    return Iterables.all(getDelegate(), predicate);
453  }
454
455  /**
456   * Returns an {@link Optional} containing the first element in this fluent iterable that satisfies
457   * the given predicate, if such an element exists.
458   *
459   * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
460   * is matched in this fluent iterable, a {@link NullPointerException} will be thrown.
461   *
462   * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()}.
463   */
464  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
465  public final Optional<@NonNull E> firstMatch(Predicate<? super E> predicate) {
466    return Iterables.<E>tryFind((Iterable<@NonNull E>) getDelegate(), predicate);
467  }
468
469  /**
470   * Returns a fluent iterable that applies {@code function} to each element of this fluent
471   * iterable.
472   *
473   * <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's
474   * iterator does. After a successful {@code remove()} call, this fluent iterable no longer
475   * contains the corresponding element.
476   *
477   * <p><b>{@code Stream} equivalent:</b> {@link Stream#map}.
478   */
479  public final <T extends @Nullable Object> FluentIterable<T> transform(
480      Function<? super E, T> function) {
481    return from(Iterables.transform(getDelegate(), function));
482  }
483
484  /**
485   * Applies {@code function} to each element of this fluent iterable and returns a fluent iterable
486   * with the concatenated combination of results. {@code function} returns an Iterable of results.
487   *
488   * <p>The returned fluent iterable's iterator supports {@code remove()} if this function-returned
489   * iterables' iterator does. After a successful {@code remove()} call, the returned fluent
490   * iterable no longer contains the corresponding element.
491   *
492   * <p><b>{@code Stream} equivalent:</b> {@link Stream#flatMap} (using a function that produces
493   * streams, not iterables).
494   *
495   * @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0)
496   */
497  public <T extends @Nullable Object> FluentIterable<T> transformAndConcat(
498      Function<? super E, ? extends Iterable<? extends T>> function) {
499    return FluentIterable.concat(transform(function));
500  }
501
502  /**
503   * Returns an {@link Optional} containing the first element in this fluent iterable. If the
504   * iterable is empty, {@code Optional.absent()} is returned.
505   *
506   * <p><b>{@code Stream} equivalent:</b> if the goal is to obtain any element, {@link
507   * Stream#findAny}; if it must specifically be the <i>first</i> element, {@code Stream#findFirst}.
508   *
509   * @throws NullPointerException if the first element is null; if this is a possibility, use {@code
510   *     iterator().next()} or {@link Iterables#getFirst} instead.
511   */
512  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
513  public final Optional<@NonNull E> first() {
514    Iterator<E> iterator = getDelegate().iterator();
515    return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.absent();
516  }
517
518  /**
519   * Returns an {@link Optional} containing the last element in this fluent iterable. If the
520   * iterable is empty, {@code Optional.absent()} is returned. If the underlying {@code iterable} is
521   * a {@link List} with {@link java.util.RandomAccess} support, then this operation is guaranteed
522   * to be {@code O(1)}.
523   *
524   * <p><b>{@code Stream} equivalent:</b> {@code stream.reduce((a, b) -> b)}.
525   *
526   * @throws NullPointerException if the last element is null; if this is a possibility, use {@link
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
566   * this fluent iterable contains fewer than {@code numberToSkip} elements, the returned fluent
567   * iterable skips all of its elements.
568   *
569   * <p>Modifications to this fluent iterable before a call to {@code iterator()} are reflected in
570   * the returned fluent iterable. That is, the iterator skips the first {@code numberToSkip}
571   * elements that exist when the iterator is created, not when {@code skip()} is called.
572   *
573   * <p>The returned fluent iterable's iterator supports {@code remove()} if the {@code Iterator} of
574   * this fluent iterable supports it. Note that it is <i>not</i> possible to delete the last
575   * skipped element by immediately calling {@code remove()} on the returned fluent iterable's
576   * iterator, as the {@code Iterator} contract states that a call to {@code * remove()} before a
577   * call to {@code next()} will throw an {@link IllegalStateException}.
578   *
579   * <p><b>{@code Stream} equivalent:</b> {@link Stream#skip} (same).
580   */
581  public final FluentIterable<E> skip(int numberToSkip) {
582    return from(Iterables.skip(getDelegate(), numberToSkip));
583  }
584
585  /**
586   * Creates a fluent iterable with the first {@code size} elements of this fluent iterable. If this
587   * fluent iterable does not contain that many elements, the returned fluent iterable will have the
588   * same behavior as this fluent iterable. The returned fluent iterable's iterator supports {@code
589   * remove()} if this fluent iterable's iterator does.
590   *
591   * <p><b>{@code Stream} equivalent:</b> {@link Stream#limit} (same).
592   *
593   * @param maxSize the maximum number of elements in the returned fluent iterable
594   * @throws IllegalArgumentException if {@code size} is negative
595   */
596  public final FluentIterable<E> limit(int maxSize) {
597    return from(Iterables.limit(getDelegate(), maxSize));
598  }
599
600  /**
601   * Determines whether this fluent iterable is empty.
602   *
603   * <p><b>{@code Stream} equivalent:</b> {@code !stream.findAny().isPresent()}.
604   */
605  public final boolean isEmpty() {
606    return !getDelegate().iterator().hasNext();
607  }
608
609  /**
610   * Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in
611   * proper sequence.
612   *
613   * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableList#toImmutableList} to {@code
614   * stream.collect()}.
615   *
616   * @throws NullPointerException if any element is {@code null}
617   * @since 14.0 (since 12.0 as {@code toImmutableList()}).
618   */
619  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
620  public final ImmutableList<@NonNull E> toList() {
621    return ImmutableList.copyOf((Iterable<@NonNull E>) getDelegate());
622  }
623
624  /**
625   * Returns an {@code ImmutableList} containing all of the elements from this {@code
626   * FluentIterable} in the order specified by {@code comparator}. To produce an {@code
627   * ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}.
628   *
629   * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableList#toImmutableList} to {@code
630   * stream.sorted(comparator).collect()}.
631   *
632   * @param comparator the function by which to sort list elements
633   * @throws NullPointerException if any element of this iterable is {@code null}
634   * @since 14.0 (since 13.0 as {@code toSortedImmutableList()}).
635   */
636  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
637  public final ImmutableList<@NonNull E> toSortedList(Comparator<? super E> comparator) {
638    return Ordering.from(comparator).immutableSortedCopy((Iterable<@NonNull E>) getDelegate());
639  }
640
641  /**
642   * Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with
643   * duplicates removed.
644   *
645   * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableSet#toImmutableSet} to {@code
646   * stream.collect()}.
647   *
648   * @throws NullPointerException if any element is {@code null}
649   * @since 14.0 (since 12.0 as {@code toImmutableSet()}).
650   */
651  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
652  public final ImmutableSet<@NonNull E> toSet() {
653    return ImmutableSet.copyOf((Iterable<@NonNull E>) getDelegate());
654  }
655
656  /**
657   * Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code
658   * FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by
659   * {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted
660   * by its natural ordering, use {@code toSortedSet(Ordering.natural())}.
661   *
662   * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableSortedSet#toImmutableSortedSet} to
663   * {@code stream.collect()}.
664   *
665   * @param comparator the function by which to sort set elements
666   * @throws NullPointerException if any element of this iterable is {@code null}
667   * @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}).
668   */
669  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
670  public final ImmutableSortedSet<@NonNull E> toSortedSet(Comparator<? super E> comparator) {
671    return ImmutableSortedSet.copyOf(comparator, (Iterable<@NonNull E>) getDelegate());
672  }
673
674  /**
675   * Returns an {@code ImmutableMultiset} containing all of the elements from this fluent iterable.
676   *
677   * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableMultiset#toImmutableMultiset} to
678   * {@code stream.collect()}.
679   *
680   * @throws NullPointerException if any element is null
681   * @since 19.0
682   */
683  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
684  public final ImmutableMultiset<@NonNull E> toMultiset() {
685    return ImmutableMultiset.copyOf((Iterable<@NonNull E>) getDelegate());
686  }
687
688  /**
689   * Returns an immutable map whose keys are the distinct elements of this {@code FluentIterable}
690   * and whose value for each key was computed by {@code valueFunction}. The map's iteration order
691   * is the order of the first appearance of each key in this iterable.
692   *
693   * <p>When there are multiple instances of a key in this iterable, it is unspecified whether
694   * {@code valueFunction} will be applied to more than one instance of that key and, if it is,
695   * which result will be mapped to that key in the returned map.
696   *
697   * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(ImmutableMap.toImmutableMap(k -> k,
698   * valueFunction))}.
699   *
700   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
701   *     valueFunction} produces {@code null} for any key
702   * @since 14.0
703   */
704  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
705  public final <V> ImmutableMap<@NonNull E, V> toMap(Function<? super E, V> valueFunction) {
706    return Maps.toMap((Iterable<@NonNull E>) getDelegate(), valueFunction);
707  }
708
709  /**
710   * Creates an index {@code ImmutableListMultimap} that contains the results of applying a
711   * specified function to each item in this {@code FluentIterable} of values. Each element of this
712   * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same
713   * size as this iterable. The key used to store that value in the multimap will be the result of
714   * calling the function on that value. The resulting multimap is created as an immutable snapshot.
715   * In the returned multimap, keys appear in the order they are first encountered, and the values
716   * corresponding to each key appear in the same order as they are encountered.
717   *
718   * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.groupingBy(keyFunction))}
719   * behaves similarly, but returns a mutable {@code Map<K, List<E>>} instead, and may not preserve
720   * the order of entries.
721   *
722   * @param keyFunction the function used to produce the key for each value
723   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
724   *     keyFunction} produces {@code null} for any key
725   * @since 14.0
726   */
727  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
728  public final <K> ImmutableListMultimap<K, @NonNull E> index(Function<? super E, K> keyFunction) {
729    return Multimaps.index((Iterable<@NonNull E>) getDelegate(), keyFunction);
730  }
731
732  /**
733   * Returns a map with the contents of this {@code FluentIterable} as its {@code values}, indexed
734   * by keys derived from those values. In other words, each input value produces an entry in the
735   * map whose key is the result of applying {@code keyFunction} to that value. These entries appear
736   * in the same order as they appeared in this fluent iterable. Example usage:
737   *
738   * <pre>{@code
739   * Color red = new Color("red", 255, 0, 0);
740   * ...
741   * FluentIterable<Color> allColors = FluentIterable.from(ImmutableSet.of(red, green, blue));
742   *
743   * Map<String, Color> colorForName = allColors.uniqueIndex(toStringFunction());
744   * assertThat(colorForName).containsEntry("red", red);
745   * }</pre>
746   *
747   * <p>If your index may associate multiple values with each key, use {@link #index(Function)
748   * index}.
749   *
750   * <p><b>{@code Stream} equivalent:</b> {@code
751   * stream.collect(ImmutableMap.toImmutableMap(keyFunction, v -> v))}.
752   *
753   * @param keyFunction the function used to produce the key for each value
754   * @return a map mapping the result of evaluating the function {@code keyFunction} on each value
755   *     in this fluent iterable to that value
756   * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
757   *     value in this fluent iterable
758   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
759   *     keyFunction} produces {@code null} for any key
760   * @since 14.0
761   */
762  @SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
763  public final <K> ImmutableMap<K, @NonNull E> uniqueIndex(Function<? super E, K> keyFunction) {
764    return Maps.uniqueIndex((Iterable<@NonNull E>) getDelegate(), keyFunction);
765  }
766
767  /**
768   * Returns an array containing all of the elements from this fluent iterable in iteration order.
769   *
770   * <p><b>{@code Stream} equivalent:</b> if an object array is acceptable, use {@code
771   * stream.toArray()}; if {@code type} is a class literal such as {@code MyType.class}, use {@code
772   * stream.toArray(MyType[]::new)}. Otherwise use {@code stream.toArray( len -> (E[])
773   * Array.newInstance(type, len))}.
774   *
775   * @param type the type of the elements
776   * @return a newly-allocated array into which all the elements of this fluent iterable have been
777   *     copied
778   */
779  @GwtIncompatible // Array.newArray(Class, int)
780  public final E[] toArray(Class<@NonNull E> type) {
781    return Iterables.<E>toArray(getDelegate(), type);
782  }
783
784  /**
785   * Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to
786   * calling {@code Iterables.addAll(collection, this)}.
787   *
788   * <p><b>{@code Stream} equivalent:</b> {@code stream.forEachOrdered(collection::add)} or {@code
789   * stream.forEach(collection::add)}.
790   *
791   * @param collection the collection to copy elements to
792   * @return {@code collection}, for convenience
793   * @since 14.0
794   */
795  @CanIgnoreReturnValue
796  public final <C extends Collection<? super E>> C copyInto(C collection) {
797    checkNotNull(collection);
798    Iterable<E> iterable = getDelegate();
799    if (iterable instanceof Collection) {
800      collection.addAll((Collection<E>) iterable);
801    } else {
802      for (E item : iterable) {
803        collection.add(item);
804      }
805    }
806    return collection;
807  }
808
809  /**
810   * Returns a {@link String} containing all of the elements of this fluent iterable joined with
811   * {@code joiner}.
812   *
813   * <p><b>{@code Stream} equivalent:</b> {@code joiner.join(stream.iterator())}, or, if you are not
814   * using any optional {@code Joiner} features, {@code
815   * stream.collect(Collectors.joining(delimiter)}.
816   *
817   * @since 18.0
818   */
819  public final String join(Joiner joiner) {
820    return joiner.join(this);
821  }
822
823  /**
824   * Returns the element at the specified position in this fluent iterable.
825   *
826   * <p><b>{@code Stream} equivalent:</b> {@code stream.skip(position).findFirst().get()} (but note
827   * that this throws different exception types, and throws an exception if {@code null} would be
828   * returned).
829   *
830   * @param position position of the element to return
831   * @return the element at the specified position in this fluent iterable
832   * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
833   *     the size of this fluent iterable
834   */
835  @ParametricNullness
836  public final E get(int position) {
837    return Iterables.get(getDelegate(), position);
838  }
839
840  /**
841   * Returns a stream of this fluent iterable's contents (similar to calling {@link
842   * Collection#stream} on a collection).
843   *
844   * <p><b>Note:</b> the earlier in the chain you can switch to {@code Stream} usage (ideally not
845   * going through {@code FluentIterable} at all), the more performant and idiomatic your code will
846   * be. This method is a transitional aid, to be used only when really necessary.
847   *
848   * @since 21.0
849   */
850  public final Stream<E> stream() {
851    return Streams.stream(getDelegate());
852  }
853
854  /** Function that transforms {@code Iterable<E>} into a fluent iterable. */
855  private static class FromIterableFunction<E extends @Nullable Object>
856      implements Function<Iterable<E>, FluentIterable<E>> {
857    @Override
858    public FluentIterable<E> apply(Iterable<E> fromObject) {
859      return FluentIterable.from(fromObject);
860    }
861  }
862}