001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.collect; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.Beta; 020import com.google.common.annotations.GwtCompatible; 021import com.google.common.annotations.GwtIncompatible; 022import com.google.common.base.Function; 023import com.google.common.base.Joiner; 024import com.google.common.base.Optional; 025import com.google.common.base.Predicate; 026import com.google.errorprone.annotations.CanIgnoreReturnValue; 027import com.google.errorprone.annotations.DoNotCall; 028import java.util.Arrays; 029import java.util.Collection; 030import java.util.Comparator; 031import java.util.Iterator; 032import java.util.List; 033import java.util.SortedSet; 034import org.checkerframework.checker.nullness.compatqual.NullableDecl; 035 036/** 037 * An expanded {@code Iterable} API, providing functionality similar to Java 8's powerful <a href= 038 * "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#package.description" 039 * >streams library</a> in a slightly different way. 040 * 041 * <p>The following types of methods are provided: 042 * 043 * <ul> 044 * <li>chaining methods which return a new {@code FluentIterable} based in some way on the 045 * contents of the current one (for example {@link #transform}) 046 * <li>element extraction methods which facilitate the retrieval of certain elements (for example 047 * {@link #last}) 048 * <li>query methods which answer questions about the {@code FluentIterable}'s contents (for 049 * example {@link #anyMatch}) 050 * <li>conversion methods which copy the {@code FluentIterable}'s contents into a new collection 051 * or array (for example {@link #toList}) 052 * </ul> 053 * 054 * <p>Several lesser-used features are currently available only as static methods on the {@link 055 * Iterables} class. 056 * 057 * <p><a id="streams"></a> 058 * 059 * <h3>Comparison to streams</h3> 060 * 061 * <p>Starting with Java 8, the core Java class libraries provide a new "Streams" library (in {@code 062 * java.util.stream}), which is similar to {@code FluentIterable} but generally more powerful. Key 063 * differences include: 064 * 065 * <ul> 066 * <li>A stream is <i>single-use</i>; it becomes invalid as soon as any "terminal operation" such 067 * as {@code findFirst()} or {@code iterator()} is invoked. (Even though {@code Stream} 068 * contains all the right method <i>signatures</i> to implement {@link Iterable}, it does not 069 * actually do so, to avoid implying repeat-iterability.) {@code FluentIterable}, on the other 070 * hand, is multiple-use, and does implement {@link Iterable}. 071 * <li>Streams offer many features not found here, including {@code min/max}, {@code distinct}, 072 * {@code reduce}, {@code sorted}, the very powerful {@code collect}, and built-in support for 073 * parallelizing stream operations. 074 * <li>{@code FluentIterable} contains several features not available on {@code Stream}, which are 075 * noted in the method descriptions below. 076 * <li>Streams include primitive-specialized variants such as {@code IntStream}, the use of which 077 * is strongly recommended. 078 * <li>Streams are standard Java, not requiring a third-party dependency (but do render your code 079 * incompatible with Java 7 and earlier). 080 * </ul> 081 * 082 * <h3>Example</h3> 083 * 084 * <p>Here is an example that accepts a list from a database call, filters it based on a predicate, 085 * transforms it by invoking {@code toString()} on each element, and returns the first 10 elements 086 * as a {@code List}: 087 * 088 * <pre>{@code 089 * ImmutableList<String> results = 090 * FluentIterable.from(database.getClientList()) 091 * .filter(Client::isActiveInLastMonth) 092 * .transform(Object::toString) 093 * .limit(10) 094 * .toList(); 095 * }</pre> 096 * 097 * The approximate stream equivalent is: 098 * 099 * <pre>{@code 100 * List<String> results = 101 * database.getClientList() 102 * .stream() 103 * .filter(Client::isActiveInLastMonth) 104 * .map(Object::toString) 105 * .limit(10) 106 * .collect(Collectors.toList()); 107 * }</pre> 108 * 109 * @author Marcin Mikosik 110 * @since 12.0 111 */ 112@GwtCompatible(emulated = true) 113public abstract class FluentIterable<E> implements Iterable<E> { 114 // We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof 115 // checks on the _original_ iterable when FluentIterable.from is used. 116 // To avoid a self retain cycle under j2objc, we store Optional.absent() instead of 117 // Optional.of(this). To access the iterator delegate, call #getDelegate(), which converts to 118 // absent() back to 'this'. 119 private final Optional<Iterable<E>> iterableDelegate; 120 121 /** Constructor for use by subclasses. */ 122 protected FluentIterable() { 123 this.iterableDelegate = Optional.absent(); 124 } 125 126 FluentIterable(Iterable<E> iterable) { 127 checkNotNull(iterable); 128 this.iterableDelegate = Optional.fromNullable(this != iterable ? iterable : null); 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> 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 @Beta 164 public static <E> FluentIterable<E> from(E[] elements) { 165 return from(Arrays.asList(elements)); 166 } 167 168 /** 169 * Construct a fluent iterable from another fluent iterable. This is obviously never necessary, 170 * but is intended to help call out cases where one migration from {@code Iterable} to {@code 171 * FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}. 172 * 173 * @deprecated instances of {@code FluentIterable} don't need to be converted to {@code 174 * FluentIterable} 175 */ 176 @Deprecated 177 @DoNotCall("instances of FluentIterable don't need to be converetd to a FluentIterable") 178 public static <E> FluentIterable<E> from(FluentIterable<E> iterable) { 179 return checkNotNull(iterable); 180 } 181 182 /** 183 * Returns a fluent iterable that combines two iterables. The returned iterable has an iterator 184 * that traverses the elements in {@code a}, followed by the elements in {@code b}. The source 185 * iterators are not polled until necessary. 186 * 187 * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 188 * iterator supports it. 189 * 190 * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}. 191 * 192 * @since 20.0 193 */ 194 @Beta 195 public static <T> FluentIterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b) { 196 return concatNoDefensiveCopy(a, b); 197 } 198 199 /** 200 * Returns a fluent iterable that combines three iterables. The returned iterable has an iterator 201 * that traverses the elements in {@code a}, followed by the elements in {@code b}, followed by 202 * the elements in {@code c}. The source iterators are not polled until necessary. 203 * 204 * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 205 * iterator supports it. 206 * 207 * <p><b>{@code Stream} equivalent:</b> use nested calls to {@link Stream#concat}, or see the 208 * advice in {@link #concat(Iterable...)}. 209 * 210 * @since 20.0 211 */ 212 @Beta 213 public static <T> 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 @Beta 233 public static <T> FluentIterable<T> concat( 234 Iterable<? extends T> a, 235 Iterable<? extends T> b, 236 Iterable<? extends T> c, 237 Iterable<? extends T> d) { 238 return concatNoDefensiveCopy(a, b, c, d); 239 } 240 241 /** 242 * Returns a fluent iterable that combines several iterables. The returned iterable has an 243 * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators 244 * are not polled until necessary. 245 * 246 * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 247 * iterator supports it. 248 * 249 * <p><b>{@code Stream} equivalent:</b> to concatenate an arbitrary number of streams, use {@code 250 * Stream.of(stream1, stream2, ...).flatMap(s -> s)}. If the sources are iterables, use {@code 251 * Stream.of(iter1, iter2, ...).flatMap(Streams::stream)}. 252 * 253 * @throws NullPointerException if any of the provided iterables is {@code null} 254 * @since 20.0 255 */ 256 @Beta 257 public static <T> FluentIterable<T> concat(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 @Beta 276 public static <T> FluentIterable<T> concat( 277 final Iterable<? extends Iterable<? extends T>> inputs) { 278 checkNotNull(inputs); 279 return new FluentIterable<T>() { 280 @Override 281 public Iterator<T> iterator() { 282 return Iterators.concat(Iterators.transform(inputs.iterator(), Iterables.<T>toIterator())); 283 } 284 }; 285 } 286 287 /** Concatenates a varargs array of iterables without making a defensive copy of the array. */ 288 private static <T> FluentIterable<T> concatNoDefensiveCopy( 289 final Iterable<? extends T>... inputs) { 290 for (Iterable<? extends T> input : inputs) { 291 checkNotNull(input); 292 } 293 return new FluentIterable<T>() { 294 @Override 295 public Iterator<T> iterator() { 296 return Iterators.concat( 297 /* lazily generate the iterators on each input only as needed */ 298 new AbstractIndexedListIterator<Iterator<? extends T>>(inputs.length) { 299 @Override 300 public Iterator<? extends T> get(int i) { 301 return inputs[i].iterator(); 302 } 303 }); 304 } 305 }; 306 } 307 308 /** 309 * Returns a fluent iterable containing no elements. 310 * 311 * <p><b>{@code Stream} equivalent:</b> {@code Stream.empty()}. 312 * 313 * @since 20.0 314 */ 315 @Beta 316 public static <E> FluentIterable<E> of() { 317 return FluentIterable.from(ImmutableList.<E>of()); 318 } 319 320 /** 321 * Returns a fluent iterable containing the specified elements in order. 322 * 323 * <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#of(Object[]) 324 * Stream.of(T...)}. 325 * 326 * @since 20.0 327 */ 328 @Beta 329 public static <E> FluentIterable<E> of(@NullableDecl E element, E... elements) { 330 return from(Lists.asList(element, elements)); 331 } 332 333 /** 334 * Returns a string representation of this fluent iterable, with the format {@code [e1, e2, ..., 335 * en]}. 336 * 337 * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.joining(", ", "[", "]"))} 338 * or (less efficiently) {@code stream.collect(Collectors.toList()).toString()}. 339 */ 340 @Override 341 public String toString() { 342 return Iterables.toString(getDelegate()); 343 } 344 345 /** 346 * Returns the number of elements in this fluent iterable. 347 * 348 * <p><b>{@code Stream} equivalent:</b> {@code stream.count()}. 349 */ 350 public final int size() { 351 return Iterables.size(getDelegate()); 352 } 353 354 /** 355 * Returns {@code true} if this fluent iterable contains any object for which {@code 356 * equals(target)} is true. 357 * 358 * <p><b>{@code Stream} equivalent:</b> {@code stream.anyMatch(Predicate.isEqual(target))}. 359 */ 360 public final boolean contains(@NullableDecl Object target) { 361 return Iterables.contains(getDelegate(), target); 362 } 363 364 /** 365 * Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of this 366 * fluent iterable. 367 * 368 * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After {@code 369 * remove()} is called, subsequent cycles omit the removed element, which is no longer in this 370 * fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until this fluent 371 * iterable is empty. 372 * 373 * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You 374 * should use an explicit {@code break} or be certain that you will eventually remove all the 375 * elements. 376 * 377 * <p><b>{@code Stream} equivalent:</b> if the source iterable has only a single element {@code 378 * e}, use {@code Stream.generate(() -> e)}. Otherwise, collect your stream into a collection and 379 * use {@code Stream.generate(() -> collection).flatMap(Collection::stream)}. 380 */ 381 public final FluentIterable<E> cycle() { 382 return from(Iterables.cycle(getDelegate())); 383 } 384 385 /** 386 * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable, 387 * followed by those of {@code other}. The iterators are not polled until necessary. 388 * 389 * <p>The returned iterable's {@code Iterator} supports {@code remove()} when the corresponding 390 * {@code Iterator} supports it. 391 * 392 * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}. 393 * 394 * @since 18.0 395 */ 396 @Beta 397 public final FluentIterable<E> append(Iterable<? extends E> other) { 398 return FluentIterable.concat(getDelegate(), other); 399 } 400 401 /** 402 * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable, 403 * followed by {@code elements}. 404 * 405 * <p><b>{@code Stream} equivalent:</b> {@code Stream.concat(thisStream, Stream.of(elements))}. 406 * 407 * @since 18.0 408 */ 409 @Beta 410 public final FluentIterable<E> append(E... elements) { 411 return FluentIterable.concat(getDelegate(), Arrays.asList(elements)); 412 } 413 414 /** 415 * Returns the elements from this fluent iterable that satisfy a predicate. The resulting fluent 416 * iterable's iterator does not support {@code remove()}. 417 * 418 * <p><b>{@code Stream} equivalent:</b> {@link Stream#filter} (same). 419 */ 420 public final FluentIterable<E> filter(Predicate<? super E> predicate) { 421 return from(Iterables.filter(getDelegate(), predicate)); 422 } 423 424 /** 425 * Returns the elements from this fluent iterable that are instances of class {@code type}. 426 * 427 * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(type::isInstance).map(type::cast)}. 428 * This does perform a little more work than necessary, so another option is to insert an 429 * unchecked cast at some later point: 430 * 431 * <pre> 432 * {@code @SuppressWarnings("unchecked") // safe because of ::isInstance check 433 * ImmutableList<NewType> result = 434 * (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());} 435 * </pre> 436 */ 437 @GwtIncompatible // Class.isInstance 438 public final <T> FluentIterable<T> filter(Class<T> type) { 439 return from(Iterables.filter(getDelegate(), type)); 440 } 441 442 /** 443 * Returns {@code true} if any element in this fluent iterable satisfies the predicate. 444 * 445 * <p><b>{@code Stream} equivalent:</b> {@link Stream#anyMatch} (same). 446 */ 447 public final boolean anyMatch(Predicate<? super E> predicate) { 448 return Iterables.any(getDelegate(), predicate); 449 } 450 451 /** 452 * Returns {@code true} if every element in this fluent iterable satisfies the predicate. If this 453 * fluent iterable is empty, {@code true} is returned. 454 * 455 * <p><b>{@code Stream} equivalent:</b> {@link Stream#allMatch} (same). 456 */ 457 public final boolean allMatch(Predicate<? super E> predicate) { 458 return Iterables.all(getDelegate(), predicate); 459 } 460 461 /** 462 * Returns an {@link Optional} containing the first element in this fluent iterable that satisfies 463 * the given predicate, if such an element exists. 464 * 465 * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} 466 * is matched in this fluent iterable, a {@link NullPointerException} will be thrown. 467 * 468 * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()}. 469 */ 470 public final Optional<E> firstMatch(Predicate<? super E> predicate) { 471 return Iterables.tryFind(getDelegate(), predicate); 472 } 473 474 /** 475 * Returns a fluent iterable that applies {@code function} to each element of this fluent 476 * iterable. 477 * 478 * <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's 479 * iterator does. After a successful {@code remove()} call, this fluent iterable no longer 480 * contains the corresponding element. 481 * 482 * <p><b>{@code Stream} equivalent:</b> {@link Stream#map}. 483 */ 484 public final <T> FluentIterable<T> transform(Function<? super E, T> function) { 485 return from(Iterables.transform(getDelegate(), function)); 486 } 487 488 /** 489 * Applies {@code function} to each element of this fluent iterable and returns a fluent iterable 490 * with the concatenated combination of results. {@code function} returns an Iterable of results. 491 * 492 * <p>The returned fluent iterable's iterator supports {@code remove()} if this function-returned 493 * iterables' iterator does. After a successful {@code remove()} call, the returned fluent 494 * iterable no longer contains the corresponding element. 495 * 496 * <p><b>{@code Stream} equivalent:</b> {@link Stream#flatMap} (using a function that produces 497 * streams, not iterables). 498 * 499 * @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0) 500 */ 501 public <T> FluentIterable<T> transformAndConcat( 502 Function<? super E, ? extends Iterable<? extends T>> function) { 503 return FluentIterable.concat(transform(function)); 504 } 505 506 /** 507 * Returns an {@link Optional} containing the first element in this fluent iterable. If the 508 * iterable is empty, {@code Optional.absent()} is returned. 509 * 510 * <p><b>{@code Stream} equivalent:</b> if the goal is to obtain any element, {@link 511 * Stream#findAny}; if it must specifically be the <i>first</i> element, {@code Stream#findFirst}. 512 * 513 * @throws NullPointerException if the first element is null; if this is a possibility, use {@code 514 * iterator().next()} or {@link Iterables#getFirst} instead. 515 */ 516 public final Optional<E> first() { 517 Iterator<E> iterator = getDelegate().iterator(); 518 return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.<E>absent(); 519 } 520 521 /** 522 * Returns an {@link Optional} containing the last element in this fluent iterable. If the 523 * iterable is empty, {@code Optional.absent()} is returned. If the underlying {@code iterable} is 524 * a {@link List} with {@link java.util.RandomAccess} support, then this operation is guaranteed 525 * to be {@code O(1)}. 526 * 527 * <p><b>{@code Stream} equivalent:</b> {@code stream.reduce((a, b) -> b)}. 528 * 529 * @throws NullPointerException if the last element is null; if this is a possibility, use {@link 530 * Iterables#getLast} instead. 531 */ 532 public final Optional<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 its 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 public final ImmutableList<E> toList() { 622 return ImmutableList.copyOf(getDelegate()); 623 } 624 625 /** 626 * Returns an {@code ImmutableList} containing all of the elements from this {@code 627 * FluentIterable} in the order specified by {@code comparator}. To produce an {@code 628 * ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}. 629 * 630 * <p><b>{@code Stream} equivalent:</b> {@code 631 * ImmutableList.copyOf(stream.sorted(comparator).iterator())}, or pass {@link 632 * ImmutableList#toImmutableList} to {@code stream.sorted(comparator).collect()}. 633 * 634 * @param comparator the function by which to sort list elements 635 * @throws NullPointerException if any element of this iterable is {@code null} 636 * @since 14.0 (since 13.0 as {@code toSortedImmutableList()}). 637 */ 638 public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) { 639 return Ordering.from(comparator).immutableSortedCopy(getDelegate()); 640 } 641 642 /** 643 * Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with 644 * duplicates removed. 645 * 646 * <p><b>{@code Stream} equivalent:</b> {@code ImmutableSet.copyOf(stream.iterator())}, or pass 647 * {@link ImmutableSet#toImmutableSet} to {@code stream.collect()}. 648 * 649 * @throws NullPointerException if any element is {@code null} 650 * @since 14.0 (since 12.0 as {@code toImmutableSet()}). 651 */ 652 public final ImmutableSet<E> toSet() { 653 return ImmutableSet.copyOf(getDelegate()); 654 } 655 656 /** 657 * Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code 658 * FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by 659 * {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted 660 * by its natural ordering, use {@code toSortedSet(Ordering.natural())}. 661 * 662 * <p><b>{@code Stream} equivalent:</b> {@code ImmutableSortedSet.copyOf(comparator, 663 * stream.iterator())}, or pass {@link ImmutableSortedSet#toImmutableSortedSet} to {@code 664 * stream.collect()}. 665 * 666 * @param comparator the function by which to sort set elements 667 * @throws NullPointerException if any element of this iterable is {@code null} 668 * @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}). 669 */ 670 public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) { 671 return ImmutableSortedSet.copyOf(comparator, getDelegate()); 672 } 673 674 /** 675 * Returns an {@code ImmutableMultiset} containing all of the elements from this fluent iterable. 676 * 677 * <p><b>{@code Stream} equivalent:</b> {@code ImmutableMultiset.copyOf(stream.iterator())}, or 678 * pass {@link ImmutableMultiset#toImmutableMultiset} to {@code stream.collect()}. 679 * 680 * @throws NullPointerException if any element is null 681 * @since 19.0 682 */ 683 public final ImmutableMultiset<E> toMultiset() { 684 return ImmutableMultiset.copyOf(getDelegate()); 685 } 686 687 /** 688 * Returns an immutable map whose keys are the distinct elements of this {@code FluentIterable} 689 * and whose value for each key was computed by {@code valueFunction}. The map's iteration order 690 * is the order of the first appearance of each key in this iterable. 691 * 692 * <p>When there are multiple instances of a key in this iterable, it is unspecified whether 693 * {@code valueFunction} will be applied to more than one instance of that key and, if it is, 694 * which result will be mapped to that key in the returned map. 695 * 696 * <p><b>{@code Stream} equivalent:</b> use {@code stream.collect(ImmutableMap.toImmutableMap(k -> 697 * k, valueFunction))}. {@code ImmutableMap.copyOf(stream.collect(Collectors.toMap(k -> k, 698 * valueFunction)))} behaves similarly, but may not preserve the order of entries. 699 * 700 * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code 701 * valueFunction} produces {@code null} for any key 702 * @since 14.0 703 */ 704 public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) { 705 return Maps.toMap(getDelegate(), valueFunction); 706 } 707 708 /** 709 * Creates an index {@code ImmutableListMultimap} that contains the results of applying a 710 * specified function to each item in this {@code FluentIterable} of values. Each element of this 711 * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same 712 * size as this iterable. The key used to store that value in the multimap will be the result of 713 * calling the function on that value. The resulting multimap is created as an immutable snapshot. 714 * In the returned multimap, keys appear in the order they are first encountered, and the values 715 * corresponding to each key appear in the same order as they are encountered. 716 * 717 * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.groupingBy(keyFunction))} 718 * behaves similarly, but returns a mutable {@code Map<K, List<E>>} instead, and may not preserve 719 * the order of entries. 720 * 721 * @param keyFunction the function used to produce the key for each value 722 * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code 723 * keyFunction} produces {@code null} for any key 724 * @since 14.0 725 */ 726 public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) { 727 return Multimaps.index(getDelegate(), keyFunction); 728 } 729 730 /** 731 * Returns a map with the contents of this {@code FluentIterable} as its {@code values}, indexed 732 * by keys derived from those values. In other words, each input value produces an entry in the 733 * map whose key is the result of applying {@code keyFunction} to that value. These entries appear 734 * in the same order as they appeared in this fluent iterable. Example usage: 735 * 736 * <pre>{@code 737 * Color red = new Color("red", 255, 0, 0); 738 * ... 739 * FluentIterable<Color> allColors = FluentIterable.from(ImmutableSet.of(red, green, blue)); 740 * 741 * Map<String, Color> colorForName = allColors.uniqueIndex(toStringFunction()); 742 * assertThat(colorForName).containsEntry("red", red); 743 * }</pre> 744 * 745 * <p>If your index may associate multiple values with each key, use {@link #index(Function) 746 * index}. 747 * 748 * <p><b>{@code Stream} equivalent:</b> use {@code 749 * stream.collect(ImmutableMap.toImmutableMap(keyFunction, v -> v))}. {@code 750 * ImmutableMap.copyOf(stream.collect(Collectors.toMap(keyFunction, v -> v)))}, but be aware that 751 * this may not preserve the order of entries. 752 * 753 * @param keyFunction the function used to produce the key for each value 754 * @return a map mapping the result of evaluating the function {@code keyFunction} on each value 755 * in this fluent iterable to that value 756 * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one 757 * value in this fluent iterable 758 * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code 759 * keyFunction} produces {@code null} for any key 760 * @since 14.0 761 */ 762 public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) { 763 return Maps.uniqueIndex(getDelegate(), keyFunction); 764 } 765 766 /** 767 * Returns an array containing all of the elements from this fluent iterable in iteration order. 768 * 769 * <p><b>{@code Stream} equivalent:</b> if an object array is acceptable, use {@code 770 * stream.toArray()}; if {@code type} is a class literal such as {@code MyType.class}, use {@code 771 * stream.toArray(MyType[]::new)}. Otherwise use {@code stream.toArray( len -> (E[]) 772 * Array.newInstance(type, len))}. 773 * 774 * @param type the type of the elements 775 * @return a newly-allocated array into which all the elements of this fluent iterable have been 776 * copied 777 */ 778 @GwtIncompatible // Array.newArray(Class, int) 779 public final E[] toArray(Class<E> type) { 780 return Iterables.toArray(getDelegate(), type); 781 } 782 783 /** 784 * Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to 785 * calling {@code Iterables.addAll(collection, this)}. 786 * 787 * <p><b>{@code Stream} equivalent:</b> {@code stream.forEachOrdered(collection::add)} or {@code 788 * stream.forEach(collection::add)}. 789 * 790 * @param collection the collection to copy elements to 791 * @return {@code collection}, for convenience 792 * @since 14.0 793 */ 794 @CanIgnoreReturnValue 795 public final <C extends Collection<? super E>> C copyInto(C collection) { 796 checkNotNull(collection); 797 Iterable<E> iterable = getDelegate(); 798 if (iterable instanceof Collection) { 799 collection.addAll(Collections2.cast(iterable)); 800 } else { 801 for (E item : iterable) { 802 collection.add(item); 803 } 804 } 805 return collection; 806 } 807 808 /** 809 * Returns a {@link String} containing all of the elements of this fluent iterable joined with 810 * {@code joiner}. 811 * 812 * <p><b>{@code Stream} equivalent:</b> {@code joiner.join(stream.iterator())}, or, if you are not 813 * using any optional {@code Joiner} features, {@code 814 * stream.collect(Collectors.joining(delimiter)}. 815 * 816 * @since 18.0 817 */ 818 @Beta 819 public final String join(Joiner joiner) { 820 return joiner.join(this); 821 } 822 823 /** 824 * Returns the element at the specified position in this fluent iterable. 825 * 826 * <p><b>{@code Stream} equivalent:</b> {@code stream.skip(position).findFirst().get()} (but note 827 * that this throws different exception types, and throws an exception if {@code null} would be 828 * returned). 829 * 830 * @param position position of the element to return 831 * @return the element at the specified position in this fluent iterable 832 * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to 833 * the size of this fluent iterable 834 */ 835 // TODO(kevinb): add @NullableDecl? 836 public final E get(int position) { 837 return Iterables.get(getDelegate(), position); 838 } 839 840 /** Function that transforms {@code Iterable<E>} into a fluent iterable. */ 841 private static class FromIterableFunction<E> implements Function<Iterable<E>, FluentIterable<E>> { 842 @Override 843 public FluentIterable<E> apply(Iterable<E> fromObject) { 844 return FluentIterable.from(fromObject); 845 } 846 } 847}