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