Coverage Summary for Class: FluentIterable (com.google.common.collect)

Class Method, % Line, %
FluentIterable 17.8% (8/45) 20.5% (16/78)
FluentIterable$1 50% (1/2) 50% (1/2)
FluentIterable$2 100% (2/2) 100% (2/2)
FluentIterable$3 0% (0/2) 0% (0/2)
FluentIterable$3$1 0% (0/2) 0% (0/2)
FluentIterable$FromIterableFunction 0% (0/2) 0% (0/2)
Total 20% (11/55) 21.6% (19/88)


1 /* 2  * Copyright (C) 2008 The Guava Authors 3  * 4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5  * in compliance with the License. You may obtain a copy of the License at 6  * 7  * http://www.apache.org/licenses/LICENSE-2.0 8  * 9  * Unless required by applicable law or agreed to in writing, software distributed under the License 10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11  * or implied. See the License for the specific language governing permissions and limitations under 12  * the License. 13  */ 14  15 package com.google.common.collect; 16  17 import static com.google.common.base.Preconditions.checkNotNull; 18  19 import com.google.common.annotations.Beta; 20 import com.google.common.annotations.GwtCompatible; 21 import com.google.common.annotations.GwtIncompatible; 22 import com.google.common.base.Function; 23 import com.google.common.base.Joiner; 24 import com.google.common.base.Optional; 25 import com.google.common.base.Predicate; 26 import com.google.errorprone.annotations.CanIgnoreReturnValue; 27 import com.google.errorprone.annotations.InlineMe; 28 import java.util.Arrays; 29 import java.util.Collection; 30 import java.util.Comparator; 31 import java.util.Iterator; 32 import java.util.List; 33 import java.util.SortedSet; 34 import java.util.stream.Stream; 35 import org.checkerframework.checker.nullness.qual.Nullable; 36  37 /** 38  * A discouraged (but not deprecated) precursor to Java's superior {@link Stream} library. 39  * 40  * <p>The following types of methods are provided: 41  * 42  * <ul> 43  * <li>chaining methods which return a new {@code FluentIterable} based in some way on the 44  * contents of the current one (for example {@link #transform}) 45  * <li>element extraction methods which facilitate the retrieval of certain elements (for example 46  * {@link #last}) 47  * <li>query methods which answer questions about the {@code FluentIterable}'s contents (for 48  * example {@link #anyMatch}) 49  * <li>conversion methods which copy the {@code FluentIterable}'s contents into a new collection 50  * or array (for example {@link #toList}) 51  * </ul> 52  * 53  * <p>Several lesser-used features are currently available only as static methods on the {@link 54  * Iterables} class. 55  * 56  * <p><a id="streams"></a> 57  * 58  * <h3>Comparison to streams</h3> 59  * 60  * <p>{@link Stream} is similar to this class, but generally more powerful, and certainly more 61  * standard. Key differences include: 62  * 63  * <ul> 64  * <li>A stream is <i>single-use</i>; it becomes invalid as soon as any "terminal operation" such 65  * as {@code findFirst()} or {@code iterator()} is invoked. (Even though {@code Stream} 66  * contains all the right method <i>signatures</i> to implement {@link Iterable}, it does not 67  * actually do so, to avoid implying repeat-iterability.) {@code FluentIterable}, on the other 68  * hand, is multiple-use, and does implement {@link Iterable}. 69  * <li>Streams offer many features not found here, including {@code min/max}, {@code distinct}, 70  * {@code reduce}, {@code sorted}, the very powerful {@code collect}, and built-in support for 71  * parallelizing stream operations. 72  * <li>{@code FluentIterable} contains several features not available on {@code Stream}, which are 73  * noted in the method descriptions below. 74  * <li>Streams include primitive-specialized variants such as {@code IntStream}, the use of which 75  * is strongly recommended. 76  * <li>Streams are standard Java, not requiring a third-party dependency. 77  * </ul> 78  * 79  * <h3>Example</h3> 80  * 81  * <p>Here is an example that accepts a list from a database call, filters it based on a predicate, 82  * transforms it by invoking {@code toString()} on each element, and returns the first 10 elements 83  * as a {@code List}: 84  * 85  * <pre>{@code 86  * ImmutableList<String> results = 87  * FluentIterable.from(database.getClientList()) 88  * .filter(Client::isActiveInLastMonth) 89  * .transform(Object::toString) 90  * .limit(10) 91  * .toList(); 92  * }</pre> 93  * 94  * The approximate stream equivalent is: 95  * 96  * <pre>{@code 97  * List<String> results = 98  * database.getClientList() 99  * .stream() 100  * .filter(Client::isActiveInLastMonth) 101  * .map(Object::toString) 102  * .limit(10) 103  * .collect(Collectors.toList()); 104  * }</pre> 105  * 106  * @author Marcin Mikosik 107  * @since 12.0 108  */ 109 @GwtCompatible(emulated = true) 110 public abstract class FluentIterable<E> implements Iterable<E> { 111  // We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof 112  // checks on the _original_ iterable when FluentIterable.from is used. 113  // To avoid a self retain cycle under j2objc, we store Optional.absent() instead of 114  // Optional.of(this). To access the iterator delegate, call #getDelegate(), which converts to 115  // absent() back to 'this'. 116  private final Optional<Iterable<E>> iterableDelegate; 117  118  /** Constructor for use by subclasses. */ 119  protected FluentIterable() { 120  this.iterableDelegate = Optional.absent(); 121  } 122  123  FluentIterable(Iterable<E> iterable) { 124  checkNotNull(iterable); 125  this.iterableDelegate = Optional.fromNullable(this != iterable ? iterable : null); 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> 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  @Beta 161  public static <E> FluentIterable<E> from(E[] elements) { 162  return from(Arrays.asList(elements)); 163  } 164  165  /** 166  * Construct a fluent iterable from another fluent iterable. This is obviously never necessary, 167  * but is intended to help call out cases where one migration from {@code Iterable} to {@code 168  * FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}. 169  * 170  * @deprecated instances of {@code FluentIterable} don't need to be converted to {@code 171  * FluentIterable} 172  */ 173  @Deprecated 174  @InlineMe( 175  replacement = "checkNotNull(iterable)", 176  staticImports = {"com.google.common.base.Preconditions.checkNotNull"}) 177  public static <E> FluentIterable<E> from(FluentIterable<E> iterable) { 178  return checkNotNull(iterable); 179  } 180  181  /** 182  * Returns a fluent iterable that combines two iterables. The returned iterable has an iterator 183  * that traverses the elements in {@code a}, followed by the elements in {@code b}. The source 184  * iterators are not polled until necessary. 185  * 186  * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 187  * iterator supports it. 188  * 189  * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}. 190  * 191  * @since 20.0 192  */ 193  @Beta 194  public static <T> FluentIterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b) { 195  return concatNoDefensiveCopy(a, b); 196  } 197  198  /** 199  * Returns a fluent iterable that combines three iterables. The returned iterable has an iterator 200  * that traverses the elements in {@code a}, followed by the elements in {@code b}, followed by 201  * the elements in {@code c}. The source iterators are not polled until necessary. 202  * 203  * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 204  * iterator supports it. 205  * 206  * <p><b>{@code Stream} equivalent:</b> use nested calls to {@link Stream#concat}, or see the 207  * advice in {@link #concat(Iterable...)}. 208  * 209  * @since 20.0 210  */ 211  @Beta 212  public static <T> FluentIterable<T> concat( 213  Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) { 214  return concatNoDefensiveCopy(a, b, c); 215  } 216  217  /** 218  * Returns a fluent iterable that combines four iterables. The returned iterable has an iterator 219  * that traverses the elements in {@code a}, followed by the elements in {@code b}, followed by 220  * the elements in {@code c}, followed by the elements in {@code d}. The source iterators are not 221  * polled until necessary. 222  * 223  * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 224  * iterator supports it. 225  * 226  * <p><b>{@code Stream} equivalent:</b> use nested calls to {@link Stream#concat}, or see the 227  * advice in {@link #concat(Iterable...)}. 228  * 229  * @since 20.0 230  */ 231  @Beta 232  public static <T> 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  @Beta 256  public static <T> FluentIterable<T> concat(Iterable<? extends T>... inputs) { 257  return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length)); 258  } 259  260  /** 261  * Returns a fluent iterable that combines several iterables. The returned iterable has an 262  * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators 263  * are not polled until necessary. 264  * 265  * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 266  * iterator supports it. The methods of the returned iterable may throw {@code 267  * NullPointerException} if any of the input iterators is {@code null}. 268  * 269  * <p><b>{@code Stream} equivalent:</b> {@code streamOfStreams.flatMap(s -> s)} or {@code 270  * streamOfIterables.flatMap(Streams::stream)}. (See {@link Streams#stream}.) 271  * 272  * @since 20.0 273  */ 274  @Beta 275  public static <T> 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(), Iterables.<T>toIterator())); 282  } 283  }; 284  } 285  286  /** Concatenates a varargs array of iterables without making a defensive copy of the array. */ 287  private static <T> 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> {@link Stream#empty}. 311  * 312  * @since 20.0 313  */ 314  @Beta 315  public static <E> FluentIterable<E> of() { 316  return FluentIterable.from(ImmutableList.<E>of()); 317  } 318  319  /** 320  * Returns a fluent iterable containing the specified elements in order. 321  * 322  * <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#of(Object[]) 323  * Stream.of(T...)}. 324  * 325  * @since 20.0 326  */ 327  @Beta 328  public static <E> FluentIterable<E> of(@Nullable E element, E... elements) { 329  return from(Lists.asList(element, elements)); 330  } 331  332  /** 333  * Returns a string representation of this fluent iterable, with the format {@code [e1, e2, ..., 334  * en]}. 335  * 336  * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.joining(", ", "[", "]"))} 337  * or (less efficiently) {@code stream.collect(Collectors.toList()).toString()}. 338  */ 339  @Override 340  public String toString() { 341  return Iterables.toString(getDelegate()); 342  } 343  344  /** 345  * Returns the number of elements in this fluent iterable. 346  * 347  * <p><b>{@code Stream} equivalent:</b> {@link Stream#count}. 348  */ 349  public final int size() { 350  return Iterables.size(getDelegate()); 351  } 352  353  /** 354  * Returns {@code true} if this fluent iterable contains any object for which {@code 355  * equals(target)} is true. 356  * 357  * <p><b>{@code Stream} equivalent:</b> {@code stream.anyMatch(Predicate.isEqual(target))}. 358  */ 359  public final boolean contains(@Nullable Object target) { 360  return Iterables.contains(getDelegate(), target); 361  } 362  363  /** 364  * Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of this 365  * fluent iterable. 366  * 367  * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After {@code 368  * remove()} is called, subsequent cycles omit the removed element, which is no longer in this 369  * fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until this fluent 370  * iterable is empty. 371  * 372  * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You 373  * should use an explicit {@code break} or be certain that you will eventually remove all the 374  * elements. 375  * 376  * <p><b>{@code Stream} equivalent:</b> if the source iterable has only a single element {@code 377  * e}, use {@code Stream.generate(() -> e)}. Otherwise, collect your stream into a collection and 378  * use {@code Stream.generate(() -> collection).flatMap(Collection::stream)}. 379  */ 380  public final FluentIterable<E> cycle() { 381  return from(Iterables.cycle(getDelegate())); 382  } 383  384  /** 385  * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable, 386  * followed by those of {@code other}. The iterators are not polled until necessary. 387  * 388  * <p>The returned iterable's {@code Iterator} supports {@code remove()} when the corresponding 389  * {@code Iterator} supports it. 390  * 391  * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}. 392  * 393  * @since 18.0 394  */ 395  @Beta 396  public final FluentIterable<E> append(Iterable<? extends E> other) { 397  return FluentIterable.concat(getDelegate(), other); 398  } 399  400  /** 401  * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable, 402  * followed by {@code elements}. 403  * 404  * <p><b>{@code Stream} equivalent:</b> {@code Stream.concat(thisStream, Stream.of(elements))}. 405  * 406  * @since 18.0 407  */ 408  @Beta 409  public final FluentIterable<E> append(E... elements) { 410  return FluentIterable.concat(getDelegate(), Arrays.asList(elements)); 411  } 412  413  /** 414  * Returns the elements from this fluent iterable that satisfy a predicate. The resulting fluent 415  * iterable's iterator does not support {@code remove()}. 416  * 417  * <p><b>{@code Stream} equivalent:</b> {@link Stream#filter} (same). 418  */ 419  public final FluentIterable<E> filter(Predicate<? super E> predicate) { 420  return from(Iterables.filter(getDelegate(), predicate)); 421  } 422  423  /** 424  * Returns the elements from this fluent iterable that are instances of class {@code type}. 425  * 426  * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(type::isInstance).map(type::cast)}. 427  * This does perform a little more work than necessary, so another option is to insert an 428  * unchecked cast at some later point: 429  * 430  * <pre> 431  * {@code @SuppressWarnings("unchecked") // safe because of ::isInstance check 432  * ImmutableList<NewType> result = 433  * (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());} 434  * </pre> 435  */ 436  @GwtIncompatible // Class.isInstance 437  public final <T> FluentIterable<T> filter(Class<T> type) { 438  return from(Iterables.filter(getDelegate(), type)); 439  } 440  441  /** 442  * Returns {@code true} if any element in this fluent iterable satisfies the predicate. 443  * 444  * <p><b>{@code Stream} equivalent:</b> {@link Stream#anyMatch} (same). 445  */ 446  public final boolean anyMatch(Predicate<? super E> predicate) { 447  return Iterables.any(getDelegate(), predicate); 448  } 449  450  /** 451  * Returns {@code true} if every element in this fluent iterable satisfies the predicate. If this 452  * fluent iterable is empty, {@code true} is returned. 453  * 454  * <p><b>{@code Stream} equivalent:</b> {@link Stream#allMatch} (same). 455  */ 456  public final boolean allMatch(Predicate<? super E> predicate) { 457  return Iterables.all(getDelegate(), predicate); 458  } 459  460  /** 461  * Returns an {@link Optional} containing the first element in this fluent iterable that satisfies 462  * the given predicate, if such an element exists. 463  * 464  * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} 465  * is matched in this fluent iterable, a {@link NullPointerException} will be thrown. 466  * 467  * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()}. 468  */ 469  public final Optional<E> firstMatch(Predicate<? super E> predicate) { 470  return Iterables.tryFind(getDelegate(), predicate); 471  } 472  473  /** 474  * Returns a fluent iterable that applies {@code function} to each element of this fluent 475  * iterable. 476  * 477  * <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's 478  * iterator does. After a successful {@code remove()} call, this fluent iterable no longer 479  * contains the corresponding element. 480  * 481  * <p><b>{@code Stream} equivalent:</b> {@link Stream#map}. 482  */ 483  public final <T> FluentIterable<T> transform(Function<? super E, T> function) { 484  return from(Iterables.transform(getDelegate(), function)); 485  } 486  487  /** 488  * Applies {@code function} to each element of this fluent iterable and returns a fluent iterable 489  * with the concatenated combination of results. {@code function} returns an Iterable of results. 490  * 491  * <p>The returned fluent iterable's iterator supports {@code remove()} if this function-returned 492  * iterables' iterator does. After a successful {@code remove()} call, the returned fluent 493  * iterable no longer contains the corresponding element. 494  * 495  * <p><b>{@code Stream} equivalent:</b> {@link Stream#flatMap} (using a function that produces 496  * streams, not iterables). 497  * 498  * @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0) 499  */ 500  public <T> FluentIterable<T> transformAndConcat( 501  Function<? super E, ? extends Iterable<? extends T>> function) { 502  return FluentIterable.concat(transform(function)); 503  } 504  505  /** 506  * Returns an {@link Optional} containing the first element in this fluent iterable. If the 507  * iterable is empty, {@code Optional.absent()} is returned. 508  * 509  * <p><b>{@code Stream} equivalent:</b> if the goal is to obtain any element, {@link 510  * Stream#findAny}; if it must specifically be the <i>first</i> element, {@code Stream#findFirst}. 511  * 512  * @throws NullPointerException if the first element is null; if this is a possibility, use {@code 513  * iterator().next()} or {@link Iterables#getFirst} instead. 514  */ 515  public final Optional<E> first() { 516  Iterator<E> iterator = getDelegate().iterator(); 517  return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.<E>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  public final Optional<E> last() { 532  // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE 533  534  // TODO(kevinb): Support a concurrently modified collection? 535  Iterable<E> iterable = getDelegate(); 536  if (iterable instanceof List) { 537  List<E> list = (List<E>) iterable; 538  if (list.isEmpty()) { 539  return Optional.absent(); 540  } 541  return Optional.of(list.get(list.size() - 1)); 542  } 543  Iterator<E> iterator = iterable.iterator(); 544  if (!iterator.hasNext()) { 545  return Optional.absent(); 546  } 547  548  /* 549  * TODO(kevinb): consider whether this "optimization" is worthwhile. Users with SortedSets tend 550  * to know they are SortedSets and probably would not call this method. 551  */ 552  if (iterable instanceof SortedSet) { 553  SortedSet<E> sortedSet = (SortedSet<E>) iterable; 554  return Optional.of(sortedSet.last()); 555  } 556  557  while (true) { 558  E current = iterator.next(); 559  if (!iterator.hasNext()) { 560  return Optional.of(current); 561  } 562  } 563  } 564  565  /** 566  * Returns a view of this fluent iterable that skips its first {@code numberToSkip} elements. If 567  * this fluent iterable contains fewer than {@code numberToSkip} elements, the returned fluent 568  * iterable skips all of its elements. 569  * 570  * <p>Modifications to this fluent iterable before a call to {@code iterator()} are reflected in 571  * the returned fluent iterable. That is, the its iterator skips the first {@code numberToSkip} 572  * elements that exist when the iterator is created, not when {@code skip()} is called. 573  * 574  * <p>The returned fluent iterable's iterator supports {@code remove()} if the {@code Iterator} of 575  * this fluent iterable supports it. Note that it is <i>not</i> possible to delete the last 576  * skipped element by immediately calling {@code remove()} on the returned fluent iterable's 577  * iterator, as the {@code Iterator} contract states that a call to {@code * remove()} before a 578  * call to {@code next()} will throw an {@link IllegalStateException}. 579  * 580  * <p><b>{@code Stream} equivalent:</b> {@link Stream#skip} (same). 581  */ 582  public final FluentIterable<E> skip(int numberToSkip) { 583  return from(Iterables.skip(getDelegate(), numberToSkip)); 584  } 585  586  /** 587  * Creates a fluent iterable with the first {@code size} elements of this fluent iterable. If this 588  * fluent iterable does not contain that many elements, the returned fluent iterable will have the 589  * same behavior as this fluent iterable. The returned fluent iterable's iterator supports {@code 590  * remove()} if this fluent iterable's iterator does. 591  * 592  * <p><b>{@code Stream} equivalent:</b> {@link Stream#limit} (same). 593  * 594  * @param maxSize the maximum number of elements in the returned fluent iterable 595  * @throws IllegalArgumentException if {@code size} is negative 596  */ 597  public final FluentIterable<E> limit(int maxSize) { 598  return from(Iterables.limit(getDelegate(), maxSize)); 599  } 600  601  /** 602  * Determines whether this fluent iterable is empty. 603  * 604  * <p><b>{@code Stream} equivalent:</b> {@code !stream.findAny().isPresent()}. 605  */ 606  public final boolean isEmpty() { 607  return !getDelegate().iterator().hasNext(); 608  } 609  610  /** 611  * Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in 612  * proper sequence. 613  * 614  * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableList#toImmutableList} to {@code 615  * stream.collect()}. 616  * 617  * @throws NullPointerException if any element is {@code null} 618  * @since 14.0 (since 12.0 as {@code toImmutableList()}). 619  */ 620  public final ImmutableList<E> toList() { 621  return ImmutableList.copyOf(getDelegate()); 622  } 623  624  /** 625  * Returns an {@code ImmutableList} containing all of the elements from this {@code 626  * FluentIterable} in the order specified by {@code comparator}. To produce an {@code 627  * ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}. 628  * 629  * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableList#toImmutableList} to {@code 630  * stream.sorted(comparator).collect()}. 631  * 632  * @param comparator the function by which to sort list elements 633  * @throws NullPointerException if any element of this iterable is {@code null} 634  * @since 14.0 (since 13.0 as {@code toSortedImmutableList()}). 635  */ 636  public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) { 637  return Ordering.from(comparator).immutableSortedCopy(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  public final ImmutableSet<E> toSet() { 651  return ImmutableSet.copyOf(getDelegate()); 652  } 653  654  /** 655  * Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code 656  * FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by 657  * {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted 658  * by its natural ordering, use {@code toSortedSet(Ordering.natural())}. 659  * 660  * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableSortedSet#toImmutableSortedSet} to 661  * {@code stream.collect()}. 662  * 663  * @param comparator the function by which to sort set elements 664  * @throws NullPointerException if any element of this iterable is {@code null} 665  * @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}). 666  */ 667  public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) { 668  return ImmutableSortedSet.copyOf(comparator, getDelegate()); 669  } 670  671  /** 672  * Returns an {@code ImmutableMultiset} containing all of the elements from this fluent iterable. 673  * 674  * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableMultiset#toImmutableMultiset} to 675  * {@code stream.collect()}. 676  * 677  * @throws NullPointerException if any element is null 678  * @since 19.0 679  */ 680  public final ImmutableMultiset<E> toMultiset() { 681  return ImmutableMultiset.copyOf(getDelegate()); 682  } 683  684  /** 685  * Returns an immutable map whose keys are the distinct elements of this {@code FluentIterable} 686  * and whose value for each key was computed by {@code valueFunction}. The map's iteration order 687  * is the order of the first appearance of each key in this iterable. 688  * 689  * <p>When there are multiple instances of a key in this iterable, it is unspecified whether 690  * {@code valueFunction} will be applied to more than one instance of that key and, if it is, 691  * which result will be mapped to that key in the returned map. 692  * 693  * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(ImmutableMap.toImmutableMap(k -> k, 694  * valueFunction))}. 695  * 696  * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code 697  * valueFunction} produces {@code null} for any key 698  * @since 14.0 699  */ 700  public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) { 701  return Maps.toMap(getDelegate(), valueFunction); 702  } 703  704  /** 705  * Creates an index {@code ImmutableListMultimap} that contains the results of applying a 706  * specified function to each item in this {@code FluentIterable} of values. Each element of this 707  * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same 708  * size as this iterable. The key used to store that value in the multimap will be the result of 709  * calling the function on that value. The resulting multimap is created as an immutable snapshot. 710  * In the returned multimap, keys appear in the order they are first encountered, and the values 711  * corresponding to each key appear in the same order as they are encountered. 712  * 713  * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.groupingBy(keyFunction))} 714  * behaves similarly, but returns a mutable {@code Map<K, List<E>>} instead, and may not preserve 715  * the order of entries). 716  * 717  * @param keyFunction the function used to produce the key for each value 718  * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code 719  * keyFunction} produces {@code null} for any key 720  * @since 14.0 721  */ 722  public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) { 723  return Multimaps.index(getDelegate(), keyFunction); 724  } 725  726  /** 727  * Returns a map with the contents of this {@code FluentIterable} as its {@code values}, indexed 728  * by keys derived from those values. In other words, each input value produces an entry in the 729  * map whose key is the result of applying {@code keyFunction} to that value. These entries appear 730  * in the same order as they appeared in this fluent iterable. Example usage: 731  * 732  * <pre>{@code 733  * Color red = new Color("red", 255, 0, 0); 734  * ... 735  * FluentIterable<Color> allColors = FluentIterable.from(ImmutableSet.of(red, green, blue)); 736  * 737  * Map<String, Color> colorForName = allColors.uniqueIndex(toStringFunction()); 738  * assertThat(colorForName).containsEntry("red", red); 739  * }</pre> 740  * 741  * <p>If your index may associate multiple values with each key, use {@link #index(Function) 742  * index}. 743  * 744  * <p><b>{@code Stream} equivalent:</b> {@code 745  * stream.collect(ImmutableMap.toImmutableMap(keyFunction, v -> v))}. 746  * 747  * @param keyFunction the function used to produce the key for each value 748  * @return a map mapping the result of evaluating the function {@code keyFunction} on each value 749  * in this fluent iterable to that value 750  * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one 751  * value in this fluent iterable 752  * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code 753  * keyFunction} produces {@code null} for any key 754  * @since 14.0 755  */ 756  public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) { 757  return Maps.uniqueIndex(getDelegate(), keyFunction); 758  } 759  760  /** 761  * Returns an array containing all of the elements from this fluent iterable in iteration order. 762  * 763  * <p><b>{@code Stream} equivalent:</b> if an object array is acceptable, use {@code 764  * stream.toArray()}; if {@code type} is a class literal such as {@code MyType.class}, use {@code 765  * stream.toArray(MyType[]::new)}. Otherwise use {@code stream.toArray( len -> (E[]) 766  * Array.newInstance(type, len))}. 767  * 768  * @param type the type of the elements 769  * @return a newly-allocated array into which all the elements of this fluent iterable have been 770  * copied 771  */ 772  @GwtIncompatible // Array.newArray(Class, int) 773  public final E[] toArray(Class<E> type) { 774  return Iterables.toArray(getDelegate(), type); 775  } 776  777  /** 778  * Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to 779  * calling {@code Iterables.addAll(collection, this)}. 780  * 781  * <p><b>{@code Stream} equivalent:</b> {@code stream.forEachOrdered(collection::add)} or {@code 782  * stream.forEach(collection::add)}. 783  * 784  * @param collection the collection to copy elements to 785  * @return {@code collection}, for convenience 786  * @since 14.0 787  */ 788  @CanIgnoreReturnValue 789  public final <C extends Collection<? super E>> C copyInto(C collection) { 790  checkNotNull(collection); 791  Iterable<E> iterable = getDelegate(); 792  if (iterable instanceof Collection) { 793  collection.addAll((Collection<E>) iterable); 794  } else { 795  for (E item : iterable) { 796  collection.add(item); 797  } 798  } 799  return collection; 800  } 801  802  /** 803  * Returns a {@link String} containing all of the elements of this fluent iterable joined with 804  * {@code joiner}. 805  * 806  * <p><b>{@code Stream} equivalent:</b> {@code joiner.join(stream.iterator())}, or, if you are not 807  * using any optional {@code Joiner} features, {@code 808  * stream.collect(Collectors.joining(delimiter)}. 809  * 810  * @since 18.0 811  */ 812  @Beta 813  public final String join(Joiner joiner) { 814  return joiner.join(this); 815  } 816  817  /** 818  * Returns the element at the specified position in this fluent iterable. 819  * 820  * <p><b>{@code Stream} equivalent:</b> {@code stream.skip(position).findFirst().get()} (but note 821  * that this throws different exception types, and throws an exception if {@code null} would be 822  * returned). 823  * 824  * @param position position of the element to return 825  * @return the element at the specified position in this fluent iterable 826  * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to 827  * the size of this fluent iterable 828  */ 829  // TODO(kevinb): add @Nullable? 830  public final E get(int position) { 831  return Iterables.get(getDelegate(), position); 832  } 833  834  /** 835  * Returns a stream of this fluent iterable's contents (similar to calling {@link 836  * Collection#stream} on a collection). 837  * 838  * <p><b>Note:</b> the earlier in the chain you can switch to {@code Stream} usage (ideally not 839  * going through {@code FluentIterable} at all), the more performant and idiomatic your code will 840  * be. This method is a transitional aid, to be used only when really necessary. 841  * 842  * @since 21.0 843  */ 844  public final Stream<E> stream() { 845  return Streams.stream(getDelegate()); 846  } 847  848  /** Function that transforms {@code Iterable<E>} into a fluent iterable. */ 849  private static class FromIterableFunction<E> implements Function<Iterable<E>, FluentIterable<E>> { 850  @Override 851  public FluentIterable<E> apply(Iterable<E> fromObject) { 852  return FluentIterable.from(fromObject); 853  } 854  } 855 }