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