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