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