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