001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkElementIndex;
021import static com.google.common.base.Preconditions.checkNotNull;
022import static com.google.common.base.Preconditions.checkPositionIndex;
023import static com.google.common.base.Preconditions.checkPositionIndexes;
024import static com.google.common.base.Preconditions.checkState;
025import static com.google.common.collect.CollectPreconditions.checkNonnegative;
026import static com.google.common.collect.CollectPreconditions.checkRemove;
027import static com.google.common.collect.Iterators.elementsEqual;
028import static java.lang.Math.min;
029
030import com.google.common.annotations.GwtCompatible;
031import com.google.common.annotations.GwtIncompatible;
032import com.google.common.annotations.J2ktIncompatible;
033import com.google.common.annotations.VisibleForTesting;
034import com.google.common.base.Function;
035import com.google.common.base.Objects;
036import com.google.common.math.IntMath;
037import com.google.common.primitives.Ints;
038import java.io.Serializable;
039import java.math.RoundingMode;
040import java.util.AbstractList;
041import java.util.AbstractSequentialList;
042import java.util.ArrayList;
043import java.util.Arrays;
044import java.util.Collection;
045import java.util.Collections;
046import java.util.Iterator;
047import java.util.LinkedList;
048import java.util.List;
049import java.util.ListIterator;
050import java.util.NoSuchElementException;
051import java.util.RandomAccess;
052import java.util.concurrent.CopyOnWriteArrayList;
053import java.util.function.Predicate;
054import org.jspecify.annotations.Nullable;
055
056/**
057 * Static utility methods pertaining to {@link List} instances. Also see this class's counterparts
058 * {@link Sets}, {@link Maps} and {@link Queues}.
059 *
060 * <p>See the Guava User Guide article on <a href=
061 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#lists">{@code Lists}</a>.
062 *
063 * @author Kevin Bourrillion
064 * @author Mike Bostock
065 * @author Louis Wasserman
066 * @since 2.0
067 */
068@GwtCompatible(emulated = true)
069public final class Lists {
070  private Lists() {}
071
072  // ArrayList
073
074  /**
075   * Creates a <i>mutable</i>, empty {@code ArrayList} instance (for Java 6 and earlier).
076   *
077   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableList#of()} instead.
078   *
079   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
080   * use the {@code ArrayList} {@linkplain ArrayList#ArrayList() constructor} directly, taking
081   * advantage of <a
082   * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond"
083   * syntax</a>.
084   */
085  @GwtCompatible(serializable = true)
086  @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
087  public static <E extends @Nullable Object> ArrayList<E> newArrayList() {
088    return new ArrayList<>();
089  }
090
091  /**
092   * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements.
093   *
094   * <p><b>Note:</b> essentially the only reason to use this method is when you will need to add or
095   * remove elements later. Otherwise, for non-null elements use {@link ImmutableList#of()} (for
096   * varargs) or {@link ImmutableList#copyOf(Object[])} (for an array) instead. If any elements
097   * might be null, or you need support for {@link List#set(int, Object)}, use {@link
098   * Arrays#asList}.
099   *
100   * <p>Note that even when you do need the ability to add or remove, this method provides only a
101   * tiny bit of syntactic sugar for {@code newArrayList(}{@link Arrays#asList asList}{@code
102   * (...))}, or for creating an empty list then calling {@link Collections#addAll}. This method is
103   * not actually very useful and will likely be deprecated in the future.
104   */
105  @SafeVarargs
106  @GwtCompatible(serializable = true)
107  @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
108  public static <E extends @Nullable Object> ArrayList<E> newArrayList(E... elements) {
109    checkNotNull(elements); // for GWT
110    // Avoid integer overflow when a large array is passed in
111    int capacity = computeArrayListCapacity(elements.length);
112    ArrayList<E> list = new ArrayList<>(capacity);
113    Collections.addAll(list, elements);
114    return list;
115  }
116
117  /**
118   * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin
119   * shortcut for creating an empty list then calling {@link Iterables#addAll}.
120   *
121   * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
122   * ImmutableList#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link
123   * FluentIterable} and call {@code elements.toList()}.)
124   *
125   * <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. Use
126   * the {@code ArrayList} {@linkplain ArrayList#ArrayList(Collection) constructor} directly, taking
127   * advantage of <a
128   * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond"
129   * syntax</a>.
130   */
131  @GwtCompatible(serializable = true)
132  @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
133  public static <E extends @Nullable Object> ArrayList<E> newArrayList(
134      Iterable<? extends E> elements) {
135    checkNotNull(elements); // for GWT
136    // Let ArrayList's sizing logic work, if possible
137    return (elements instanceof Collection)
138        ? new ArrayList<>((Collection<? extends E>) elements)
139        : newArrayList(elements.iterator());
140  }
141
142  /**
143   * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin
144   * shortcut for creating an empty list and then calling {@link Iterators#addAll}.
145   *
146   * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
147   * ImmutableList#copyOf(Iterator)} instead.
148   */
149  @GwtCompatible(serializable = true)
150  @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
151  public static <E extends @Nullable Object> ArrayList<E> newArrayList(
152      Iterator<? extends E> elements) {
153    ArrayList<E> list = newArrayList();
154    Iterators.addAll(list, elements);
155    return list;
156  }
157
158  @VisibleForTesting
159  static int computeArrayListCapacity(int arraySize) {
160    checkNonnegative(arraySize, "arraySize");
161
162    // TODO(kevinb): Figure out the right behavior, and document it
163    return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
164  }
165
166  /**
167   * Creates an {@code ArrayList} instance backed by an array with the specified initial size;
168   * simply delegates to {@link ArrayList#ArrayList(int)}.
169   *
170   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
171   * use {@code new }{@link ArrayList#ArrayList(int) ArrayList}{@code <>(int)} directly, taking
172   * advantage of <a
173   * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond"
174   * syntax</a>. (Unlike here, there is no risk of overload ambiguity, since the {@code ArrayList}
175   * constructors very wisely did not accept varargs.)
176   *
177   * @param initialArraySize the exact size of the initial backing array for the returned array list
178   *     ({@code ArrayList} documentation calls this value the "capacity")
179   * @return a new, empty {@code ArrayList} which is guaranteed not to resize itself unless its size
180   *     reaches {@code initialArraySize + 1}
181   * @throws IllegalArgumentException if {@code initialArraySize} is negative
182   */
183  @GwtCompatible(serializable = true)
184  @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
185  public static <E extends @Nullable Object> ArrayList<E> newArrayListWithCapacity(
186      int initialArraySize) {
187    checkNonnegative(initialArraySize, "initialArraySize"); // for GWT.
188    return new ArrayList<>(initialArraySize);
189  }
190
191  /**
192   * Creates an {@code ArrayList} instance to hold {@code estimatedSize} elements, <i>plus</i> an
193   * unspecified amount of padding; you almost certainly mean to call {@link
194   * #newArrayListWithCapacity} (see that method for further advice on usage).
195   *
196   * <p><b>Note:</b> This method will soon be deprecated. Even in the rare case that you do want
197   * some amount of padding, it's best if you choose your desired amount explicitly.
198   *
199   * @param estimatedSize an estimate of the eventual {@link List#size()} of the new list
200   * @return a new, empty {@code ArrayList}, sized appropriately to hold the estimated number of
201   *     elements
202   * @throws IllegalArgumentException if {@code estimatedSize} is negative
203   */
204  @GwtCompatible(serializable = true)
205  @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
206  public static <E extends @Nullable Object> ArrayList<E> newArrayListWithExpectedSize(
207      int estimatedSize) {
208    return new ArrayList<>(computeArrayListCapacity(estimatedSize));
209  }
210
211  // LinkedList
212
213  /**
214   * Creates a <i>mutable</i>, empty {@code LinkedList} instance (for Java 6 and earlier).
215   *
216   * <p><b>Note:</b> if you won't be adding any elements to the list, use {@link ImmutableList#of()}
217   * instead.
218   *
219   * <p><b>Performance note:</b> {@link ArrayList} and {@link java.util.ArrayDeque} consistently
220   * outperform {@code LinkedList} except in certain rare and specific situations. Unless you have
221   * spent a lot of time benchmarking your specific needs, use one of those instead.
222   *
223   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
224   * use the {@code LinkedList} {@linkplain LinkedList#LinkedList() constructor} directly, taking
225   * advantage of <a
226   * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond"
227   * syntax</a>.
228   */
229  @GwtCompatible(serializable = true)
230  @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
231  public static <E extends @Nullable Object> LinkedList<E> newLinkedList() {
232    return new LinkedList<>();
233  }
234
235  /**
236   * Creates a <i>mutable</i> {@code LinkedList} instance containing the given elements; a very thin
237   * shortcut for creating an empty list then calling {@link Iterables#addAll}.
238   *
239   * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
240   * ImmutableList#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link
241   * FluentIterable} and call {@code elements.toList()}.)
242   *
243   * <p><b>Performance note:</b> {@link ArrayList} and {@link java.util.ArrayDeque} consistently
244   * outperform {@code LinkedList} except in certain rare and specific situations. Unless you have
245   * spent a lot of time benchmarking your specific needs, use one of those instead.
246   *
247   * <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. Use
248   * the {@code LinkedList} {@linkplain LinkedList#LinkedList(Collection) constructor} directly,
249   * taking advantage of <a
250   * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond"
251   * syntax</a>.
252   */
253  @GwtCompatible(serializable = true)
254  @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
255  public static <E extends @Nullable Object> LinkedList<E> newLinkedList(
256      Iterable<? extends E> elements) {
257    LinkedList<E> list = newLinkedList();
258    Iterables.addAll(list, elements);
259    return list;
260  }
261
262  /**
263   * Creates an empty {@code CopyOnWriteArrayList} instance.
264   *
265   * <p><b>Note:</b> if you need an immutable empty {@link List}, use {@link Collections#emptyList}
266   * instead.
267   *
268   * @return a new, empty {@code CopyOnWriteArrayList}
269   * @since 12.0
270   */
271  @J2ktIncompatible
272  @GwtIncompatible // CopyOnWriteArrayList
273  public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
274    return new CopyOnWriteArrayList<>();
275  }
276
277  /**
278   * Creates a {@code CopyOnWriteArrayList} instance containing the given elements.
279   *
280   * @param elements the elements that the list should contain, in order
281   * @return a new {@code CopyOnWriteArrayList} containing those elements
282   * @since 12.0
283   */
284  @J2ktIncompatible
285  @GwtIncompatible // CopyOnWriteArrayList
286  public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(
287      Iterable<? extends E> elements) {
288    // We copy elements to an ArrayList first, rather than incurring the
289    // quadratic cost of adding them to the COWAL directly.
290    Collection<? extends E> elementsCollection =
291        (elements instanceof Collection)
292            ? (Collection<? extends E>) elements
293            : newArrayList(elements);
294    return new CopyOnWriteArrayList<>(elementsCollection);
295  }
296
297  /**
298   * Returns an unmodifiable list containing the specified first element and backed by the specified
299   * array of additional elements. Changes to the {@code rest} array will be reflected in the
300   * returned list. Unlike {@link Arrays#asList}, the returned list is unmodifiable.
301   *
302   * <p>This is useful when a varargs method needs to use a signature such as {@code (Foo firstFoo,
303   * Foo... moreFoos)}, in order to avoid overload ambiguity or to enforce a minimum argument count.
304   *
305   * <p>The returned list is serializable and implements {@link RandomAccess}.
306   *
307   * @param first the first element
308   * @param rest an array of additional elements, possibly empty
309   * @return an unmodifiable list containing the specified elements
310   */
311  public static <E extends @Nullable Object> List<E> asList(@ParametricNullness E first, E[] rest) {
312    return new OnePlusArrayList<>(first, rest);
313  }
314
315  /**
316   * Returns an unmodifiable list containing the specified first and second element, and backed by
317   * the specified array of additional elements. Changes to the {@code rest} array will be reflected
318   * in the returned list. Unlike {@link Arrays#asList}, the returned list is unmodifiable.
319   *
320   * <p>This is useful when a varargs method needs to use a signature such as {@code (Foo firstFoo,
321   * Foo secondFoo, Foo... moreFoos)}, in order to avoid overload ambiguity or to enforce a minimum
322   * argument count.
323   *
324   * <p>The returned list is serializable and implements {@link RandomAccess}.
325   *
326   * @param first the first element
327   * @param second the second element
328   * @param rest an array of additional elements, possibly empty
329   * @return an unmodifiable list containing the specified elements
330   */
331  public static <E extends @Nullable Object> List<E> asList(
332      @ParametricNullness E first, @ParametricNullness E second, E[] rest) {
333    return new TwoPlusArrayList<>(first, second, rest);
334  }
335
336  /**
337   * @see Lists#asList(Object, Object[])
338   */
339  private static class OnePlusArrayList<E extends @Nullable Object> extends AbstractList<E>
340      implements Serializable, RandomAccess {
341    @ParametricNullness final E first;
342    final E[] rest;
343
344    OnePlusArrayList(@ParametricNullness E first, E[] rest) {
345      this.first = first;
346      this.rest = checkNotNull(rest);
347    }
348
349    @Override
350    public int size() {
351      return IntMath.saturatedAdd(rest.length, 1);
352    }
353
354    @Override
355    @ParametricNullness
356    public E get(int index) {
357      // check explicitly so the IOOBE will have the right message
358      checkElementIndex(index, size());
359      return (index == 0) ? first : rest[index - 1];
360    }
361
362    @J2ktIncompatible private static final long serialVersionUID = 0;
363  }
364
365  /**
366   * @see Lists#asList(Object, Object, Object[])
367   */
368  private static class TwoPlusArrayList<E extends @Nullable Object> extends AbstractList<E>
369      implements Serializable, RandomAccess {
370    @ParametricNullness final E first;
371    @ParametricNullness final E second;
372    final E[] rest;
373
374    TwoPlusArrayList(@ParametricNullness E first, @ParametricNullness E second, E[] rest) {
375      this.first = first;
376      this.second = second;
377      this.rest = checkNotNull(rest);
378    }
379
380    @Override
381    public int size() {
382      return IntMath.saturatedAdd(rest.length, 2);
383    }
384
385    @Override
386    @ParametricNullness
387    public E get(int index) {
388      switch (index) {
389        case 0:
390          return first;
391        case 1:
392          return second;
393        default:
394          // check explicitly so the IOOBE will have the right message
395          checkElementIndex(index, size());
396          return rest[index - 2];
397      }
398    }
399
400    @J2ktIncompatible private static final long serialVersionUID = 0;
401  }
402
403  /**
404   * Returns every possible list that can be formed by choosing one element from each of the given
405   * lists in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
406   * product</a>" of the lists. For example:
407   *
408   * <pre>{@code
409   * Lists.cartesianProduct(ImmutableList.of(
410   *     ImmutableList.of(1, 2),
411   *     ImmutableList.of("A", "B", "C")))
412   * }</pre>
413   *
414   * <p>returns a list containing six lists in the following order:
415   *
416   * <ul>
417   *   <li>{@code ImmutableList.of(1, "A")}
418   *   <li>{@code ImmutableList.of(1, "B")}
419   *   <li>{@code ImmutableList.of(1, "C")}
420   *   <li>{@code ImmutableList.of(2, "A")}
421   *   <li>{@code ImmutableList.of(2, "B")}
422   *   <li>{@code ImmutableList.of(2, "C")}
423   * </ul>
424   *
425   * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian
426   * products that you would get from nesting for loops:
427   *
428   * <pre>{@code
429   * for (B b0 : lists.get(0)) {
430   *   for (B b1 : lists.get(1)) {
431   *     ...
432   *     ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
433   *     // operate on tuple
434   *   }
435   * }
436   * }</pre>
437   *
438   * <p>Note that if any input list is empty, the Cartesian product will also be empty. If no lists
439   * at all are provided (an empty list), the resulting Cartesian product has one element, an empty
440   * list (counter-intuitive, but mathematically consistent).
441   *
442   * <p><i>Performance notes:</i> while the cartesian product of lists of size {@code m, n, p} is a
443   * list of size {@code m x n x p}, its actual memory consumption is much smaller. When the
444   * cartesian product is constructed, the input lists are merely copied. Only as the resulting list
445   * is iterated are the individual lists created, and these are not retained after iteration.
446   *
447   * @param lists the lists to choose elements from, in the order that the elements chosen from
448   *     those lists should appear in the resulting lists
449   * @param <B> any common base class shared by all axes (often just {@link Object})
450   * @return the Cartesian product, as an immutable list containing immutable lists
451   * @throws IllegalArgumentException if the size of the cartesian product would be greater than
452   *     {@link Integer#MAX_VALUE}
453   * @throws NullPointerException if {@code lists}, any one of the {@code lists}, or any element of
454   *     a provided list is null
455   * @since 19.0
456   */
457  public static <B> List<List<B>> cartesianProduct(List<? extends List<? extends B>> lists) {
458    return CartesianList.create(lists);
459  }
460
461  /**
462   * Returns every possible list that can be formed by choosing one element from each of the given
463   * lists in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
464   * product</a>" of the lists. For example:
465   *
466   * <pre>{@code
467   * Lists.cartesianProduct(ImmutableList.of(
468   *     ImmutableList.of(1, 2),
469   *     ImmutableList.of("A", "B", "C")))
470   * }</pre>
471   *
472   * <p>returns a list containing six lists in the following order:
473   *
474   * <ul>
475   *   <li>{@code ImmutableList.of(1, "A")}
476   *   <li>{@code ImmutableList.of(1, "B")}
477   *   <li>{@code ImmutableList.of(1, "C")}
478   *   <li>{@code ImmutableList.of(2, "A")}
479   *   <li>{@code ImmutableList.of(2, "B")}
480   *   <li>{@code ImmutableList.of(2, "C")}
481   * </ul>
482   *
483   * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian
484   * products that you would get from nesting for loops:
485   *
486   * <pre>{@code
487   * for (B b0 : lists.get(0)) {
488   *   for (B b1 : lists.get(1)) {
489   *     ...
490   *     ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
491   *     // operate on tuple
492   *   }
493   * }
494   * }</pre>
495   *
496   * <p>Note that if any input list is empty, the Cartesian product will also be empty. If no lists
497   * at all are provided (an empty list), the resulting Cartesian product has one element, an empty
498   * list (counter-intuitive, but mathematically consistent).
499   *
500   * <p><i>Performance notes:</i> while the cartesian product of lists of size {@code m, n, p} is a
501   * list of size {@code m x n x p}, its actual memory consumption is much smaller. When the
502   * cartesian product is constructed, the input lists are merely copied. Only as the resulting list
503   * is iterated are the individual lists created, and these are not retained after iteration.
504   *
505   * @param lists the lists to choose elements from, in the order that the elements chosen from
506   *     those lists should appear in the resulting lists
507   * @param <B> any common base class shared by all axes (often just {@link Object})
508   * @return the Cartesian product, as an immutable list containing immutable lists
509   * @throws IllegalArgumentException if the size of the cartesian product would be greater than
510   *     {@link Integer#MAX_VALUE}
511   * @throws NullPointerException if {@code lists}, any one of the {@code lists}, or any element of
512   *     a provided list is null
513   * @since 19.0
514   */
515  @SafeVarargs
516  public static <B> List<List<B>> cartesianProduct(List<? extends B>... lists) {
517    return cartesianProduct(Arrays.asList(lists));
518  }
519
520  /**
521   * Returns a list that applies {@code function} to each element of {@code fromList}. The returned
522   * list is a transformed view of {@code fromList}; changes to {@code fromList} will be reflected
523   * in the returned list and vice versa.
524   *
525   * <p>Since functions are not reversible, the transform is one-way and new items cannot be stored
526   * in the returned list. The {@code add}, {@code addAll} and {@code set} methods are unsupported
527   * in the returned list.
528   *
529   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned list
530   * to be a view, but it means that the function will be applied many times for bulk operations
531   * like {@link List#contains} and {@link List#hashCode}. For this to perform well, {@code
532   * function} should be fast. To avoid lazy evaluation when the returned list doesn't need to be a
533   * view, copy the returned list into a new list of your choosing.
534   *
535   * <p>If {@code fromList} implements {@link RandomAccess}, so will the returned list. The returned
536   * list is threadsafe if the supplied list and function are.
537   *
538   * <p>If only a {@code Collection} or {@code Iterable} input is available, use {@link
539   * Collections2#transform} or {@link Iterables#transform}.
540   *
541   * <p><b>Note:</b> serializing the returned list is implemented by serializing {@code fromList},
542   * its contents, and {@code function} -- <i>not</i> by serializing the transformed values. This
543   * can lead to surprising behavior, so serializing the returned list is <b>not recommended</b>.
544   * Instead, copy the list using {@link ImmutableList#copyOf(Collection)} (for example), then
545   * serialize the copy. Other methods similar to this do not implement serialization at all for
546   * this reason.
547   *
548   * <p><b>Java 8+ users:</b> many use cases for this method are better addressed by {@link
549   * java.util.stream.Stream#map}. This method is not being deprecated, but we gently encourage you
550   * to migrate to streams.
551   */
552  public static <F extends @Nullable Object, T extends @Nullable Object> List<T> transform(
553      List<F> fromList, Function<? super F, ? extends T> function) {
554    return (fromList instanceof RandomAccess)
555        ? new TransformingRandomAccessList<>(fromList, function)
556        : new TransformingSequentialList<>(fromList, function);
557  }
558
559  /**
560   * Implementation of a sequential transforming list.
561   *
562   * @see Lists#transform
563   */
564  private static class TransformingSequentialList<
565          F extends @Nullable Object, T extends @Nullable Object>
566      extends AbstractSequentialList<T> implements Serializable {
567    final List<F> fromList;
568    final Function<? super F, ? extends T> function;
569
570    TransformingSequentialList(List<F> fromList, Function<? super F, ? extends T> function) {
571      this.fromList = checkNotNull(fromList);
572      this.function = checkNotNull(function);
573    }
574
575    /**
576     * The default implementation inherited is based on iteration and removal of each element which
577     * can be overkill. That's why we forward this call directly to the backing list.
578     */
579    @Override
580    protected void removeRange(int fromIndex, int toIndex) {
581      fromList.subList(fromIndex, toIndex).clear();
582    }
583
584    @Override
585    public int size() {
586      return fromList.size();
587    }
588
589    @Override
590    public boolean isEmpty() {
591      return fromList.isEmpty();
592    }
593
594    @Override
595    public ListIterator<T> listIterator(final int index) {
596      return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
597        @Override
598        @ParametricNullness
599        T transform(@ParametricNullness F from) {
600          return function.apply(from);
601        }
602      };
603    }
604
605    @Override
606    public boolean removeIf(Predicate<? super T> filter) {
607      checkNotNull(filter);
608      return fromList.removeIf(element -> filter.test(function.apply(element)));
609    }
610
611    private static final long serialVersionUID = 0;
612  }
613
614  /**
615   * Implementation of a transforming random access list. We try to make as many of these methods
616   * pass-through to the source list as possible so that the performance characteristics of the
617   * source list and transformed list are similar.
618   *
619   * @see Lists#transform
620   */
621  private static class TransformingRandomAccessList<
622          F extends @Nullable Object, T extends @Nullable Object>
623      extends AbstractList<T> implements RandomAccess, Serializable {
624    final List<F> fromList;
625    final Function<? super F, ? extends T> function;
626
627    TransformingRandomAccessList(List<F> fromList, Function<? super F, ? extends T> function) {
628      this.fromList = checkNotNull(fromList);
629      this.function = checkNotNull(function);
630    }
631
632    /**
633     * The default implementation inherited is based on iteration and removal of each element which
634     * can be overkill. That's why we forward this call directly to the backing list.
635     */
636    @Override
637    protected void removeRange(int fromIndex, int toIndex) {
638      fromList.subList(fromIndex, toIndex).clear();
639    }
640
641    @Override
642    @ParametricNullness
643    public T get(int index) {
644      return function.apply(fromList.get(index));
645    }
646
647    @Override
648    public Iterator<T> iterator() {
649      return listIterator();
650    }
651
652    @Override
653    public ListIterator<T> listIterator(int index) {
654      return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
655        @Override
656        T transform(F from) {
657          return function.apply(from);
658        }
659      };
660    }
661
662    @Override
663    public boolean isEmpty() {
664      return fromList.isEmpty();
665    }
666
667    @Override
668    public boolean removeIf(Predicate<? super T> filter) {
669      checkNotNull(filter);
670      return fromList.removeIf(element -> filter.test(function.apply(element)));
671    }
672
673    @Override
674    @ParametricNullness
675    public T remove(int index) {
676      return function.apply(fromList.remove(index));
677    }
678
679    @Override
680    public int size() {
681      return fromList.size();
682    }
683
684    private static final long serialVersionUID = 0;
685  }
686
687  /**
688   * Returns consecutive {@linkplain List#subList(int, int) sublists} of a list, each of the same
689   * size (the final list may be smaller). For example, partitioning a list containing {@code [a, b,
690   * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list
691   * containing two inner lists of three and two elements, all in the original order.
692   *
693   * <p>The outer list is unmodifiable, but reflects the latest state of the source list. The inner
694   * lists are sublist views of the original list, produced on demand using {@link List#subList(int,
695   * int)}, and are subject to all the usual caveats about modification as explained in that API.
696   *
697   * @param list the list to return consecutive sublists of
698   * @param size the desired size of each sublist (the last may be smaller)
699   * @return a list of consecutive sublists
700   * @throws IllegalArgumentException if {@code partitionSize} is nonpositive
701   */
702  public static <T extends @Nullable Object> List<List<T>> partition(List<T> list, int size) {
703    checkNotNull(list);
704    checkArgument(size > 0);
705    return (list instanceof RandomAccess)
706        ? new RandomAccessPartition<>(list, size)
707        : new Partition<>(list, size);
708  }
709
710  private static class Partition<T extends @Nullable Object> extends AbstractList<List<T>> {
711    final List<T> list;
712    final int size;
713
714    Partition(List<T> list, int size) {
715      this.list = list;
716      this.size = size;
717    }
718
719    @Override
720    public List<T> get(int index) {
721      checkElementIndex(index, size());
722      int start = index * size;
723      int end = min(start + size, list.size());
724      return list.subList(start, end);
725    }
726
727    @Override
728    public int size() {
729      return IntMath.divide(list.size(), size, RoundingMode.CEILING);
730    }
731
732    @Override
733    public boolean isEmpty() {
734      return list.isEmpty();
735    }
736  }
737
738  private static class RandomAccessPartition<T extends @Nullable Object> extends Partition<T>
739      implements RandomAccess {
740    RandomAccessPartition(List<T> list, int size) {
741      super(list, size);
742    }
743  }
744
745  /**
746   * Returns a view of the specified string as an immutable list of {@code Character} values.
747   *
748   * @since 7.0
749   */
750  public static ImmutableList<Character> charactersOf(String string) {
751    return new StringAsImmutableList(checkNotNull(string));
752  }
753
754  /**
755   * Returns a view of the specified {@code CharSequence} as a {@code List<Character>}, viewing
756   * {@code sequence} as a sequence of Unicode code units. The view does not support any
757   * modification operations, but reflects any changes to the underlying character sequence.
758   *
759   * @param sequence the character sequence to view as a {@code List} of characters
760   * @return an {@code List<Character>} view of the character sequence
761   * @since 7.0
762   */
763  public static List<Character> charactersOf(CharSequence sequence) {
764    return new CharSequenceAsList(checkNotNull(sequence));
765  }
766
767  @SuppressWarnings("serial") // serialized using ImmutableList serialization
768  private static final class StringAsImmutableList extends ImmutableList<Character> {
769
770    private final String string;
771
772    StringAsImmutableList(String string) {
773      this.string = string;
774    }
775
776    @Override
777    public int indexOf(@Nullable Object object) {
778      return (object instanceof Character) ? string.indexOf((Character) object) : -1;
779    }
780
781    @Override
782    public int lastIndexOf(@Nullable Object object) {
783      return (object instanceof Character) ? string.lastIndexOf((Character) object) : -1;
784    }
785
786    @Override
787    public ImmutableList<Character> subList(int fromIndex, int toIndex) {
788      checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
789      return charactersOf(string.substring(fromIndex, toIndex));
790    }
791
792    @Override
793    boolean isPartialView() {
794      return false;
795    }
796
797    @Override
798    public Character get(int index) {
799      checkElementIndex(index, size()); // for GWT
800      return string.charAt(index);
801    }
802
803    @Override
804    public int size() {
805      return string.length();
806    }
807
808    // redeclare to help optimizers with b/310253115
809    @SuppressWarnings("RedundantOverride")
810    @Override
811    @J2ktIncompatible // serialization
812    @GwtIncompatible // serialization
813    Object writeReplace() {
814      return super.writeReplace();
815    }
816  }
817
818  private static final class CharSequenceAsList extends AbstractList<Character> {
819    private final CharSequence sequence;
820
821    CharSequenceAsList(CharSequence sequence) {
822      this.sequence = sequence;
823    }
824
825    @Override
826    public Character get(int index) {
827      checkElementIndex(index, size()); // for GWT
828      return sequence.charAt(index);
829    }
830
831    @Override
832    public int size() {
833      return sequence.length();
834    }
835  }
836
837  /**
838   * Returns a reversed view of the specified list. For example, {@code
839   * Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3, 2, 1}. The returned
840   * list is backed by this list, so changes in the returned list are reflected in this list, and
841   * vice-versa. The returned list supports all of the optional list operations supported by this
842   * list.
843   *
844   * <p>The returned list is random-access if the specified list is random access.
845   *
846   * @since 7.0
847   */
848  public static <T extends @Nullable Object> List<T> reverse(List<T> list) {
849    if (list instanceof ImmutableList) {
850      // Avoid nullness warnings.
851      List<?> reversed = ((ImmutableList<?>) list).reverse();
852      @SuppressWarnings("unchecked")
853      List<T> result = (List<T>) reversed;
854      return result;
855    } else if (list instanceof ReverseList) {
856      return ((ReverseList<T>) list).getForwardList();
857    } else if (list instanceof RandomAccess) {
858      return new RandomAccessReverseList<>(list);
859    } else {
860      return new ReverseList<>(list);
861    }
862  }
863
864  private static class ReverseList<T extends @Nullable Object> extends AbstractList<T> {
865    private final List<T> forwardList;
866
867    ReverseList(List<T> forwardList) {
868      this.forwardList = checkNotNull(forwardList);
869    }
870
871    List<T> getForwardList() {
872      return forwardList;
873    }
874
875    private int reverseIndex(int index) {
876      int size = size();
877      checkElementIndex(index, size);
878      return (size - 1) - index;
879    }
880
881    private int reversePosition(int index) {
882      int size = size();
883      checkPositionIndex(index, size);
884      return size - index;
885    }
886
887    @Override
888    public void add(int index, @ParametricNullness T element) {
889      forwardList.add(reversePosition(index), element);
890    }
891
892    @Override
893    public void clear() {
894      forwardList.clear();
895    }
896
897    @Override
898    @ParametricNullness
899    public T remove(int index) {
900      return forwardList.remove(reverseIndex(index));
901    }
902
903    @Override
904    protected void removeRange(int fromIndex, int toIndex) {
905      subList(fromIndex, toIndex).clear();
906    }
907
908    @Override
909    @ParametricNullness
910    public T set(int index, @ParametricNullness T element) {
911      return forwardList.set(reverseIndex(index), element);
912    }
913
914    @Override
915    @ParametricNullness
916    public T get(int index) {
917      return forwardList.get(reverseIndex(index));
918    }
919
920    @Override
921    public int size() {
922      return forwardList.size();
923    }
924
925    @Override
926    public List<T> subList(int fromIndex, int toIndex) {
927      checkPositionIndexes(fromIndex, toIndex, size());
928      return reverse(forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)));
929    }
930
931    @Override
932    public Iterator<T> iterator() {
933      return listIterator();
934    }
935
936    @Override
937    public ListIterator<T> listIterator(int index) {
938      int start = reversePosition(index);
939      final ListIterator<T> forwardIterator = forwardList.listIterator(start);
940      return new ListIterator<T>() {
941
942        boolean canRemoveOrSet;
943
944        @Override
945        public void add(@ParametricNullness T e) {
946          forwardIterator.add(e);
947          forwardIterator.previous();
948          canRemoveOrSet = false;
949        }
950
951        @Override
952        public boolean hasNext() {
953          return forwardIterator.hasPrevious();
954        }
955
956        @Override
957        public boolean hasPrevious() {
958          return forwardIterator.hasNext();
959        }
960
961        @Override
962        @ParametricNullness
963        public T next() {
964          if (!hasNext()) {
965            throw new NoSuchElementException();
966          }
967          canRemoveOrSet = true;
968          return forwardIterator.previous();
969        }
970
971        @Override
972        public int nextIndex() {
973          return reversePosition(forwardIterator.nextIndex());
974        }
975
976        @Override
977        @ParametricNullness
978        public T previous() {
979          if (!hasPrevious()) {
980            throw new NoSuchElementException();
981          }
982          canRemoveOrSet = true;
983          return forwardIterator.next();
984        }
985
986        @Override
987        public int previousIndex() {
988          return nextIndex() - 1;
989        }
990
991        @Override
992        public void remove() {
993          checkRemove(canRemoveOrSet);
994          forwardIterator.remove();
995          canRemoveOrSet = false;
996        }
997
998        @Override
999        public void set(@ParametricNullness T e) {
1000          checkState(canRemoveOrSet);
1001          forwardIterator.set(e);
1002        }
1003      };
1004    }
1005  }
1006
1007  private static class RandomAccessReverseList<T extends @Nullable Object> extends ReverseList<T>
1008      implements RandomAccess {
1009    RandomAccessReverseList(List<T> forwardList) {
1010      super(forwardList);
1011    }
1012  }
1013
1014  /** An implementation of {@link List#hashCode()}. */
1015  static int hashCodeImpl(List<?> list) {
1016    // TODO(lowasser): worth optimizing for RandomAccess?
1017    int hashCode = 1;
1018    for (Object o : list) {
1019      hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
1020
1021      hashCode = ~~hashCode;
1022      // needed to deal with GWT integer overflow
1023    }
1024    return hashCode;
1025  }
1026
1027  /** An implementation of {@link List#equals(Object)}. */
1028  static boolean equalsImpl(List<?> thisList, @Nullable Object other) {
1029    if (other == checkNotNull(thisList)) {
1030      return true;
1031    }
1032    if (!(other instanceof List)) {
1033      return false;
1034    }
1035    List<?> otherList = (List<?>) other;
1036    int size = thisList.size();
1037    if (size != otherList.size()) {
1038      return false;
1039    }
1040    if (thisList instanceof RandomAccess && otherList instanceof RandomAccess) {
1041      // avoid allocation and use the faster loop
1042      for (int i = 0; i < size; i++) {
1043        if (!Objects.equal(thisList.get(i), otherList.get(i))) {
1044          return false;
1045        }
1046      }
1047      return true;
1048    } else {
1049      return elementsEqual(thisList.iterator(), otherList.iterator());
1050    }
1051  }
1052
1053  /** An implementation of {@link List#addAll(int, Collection)}. */
1054  static <E extends @Nullable Object> boolean addAllImpl(
1055      List<E> list, int index, Iterable<? extends E> elements) {
1056    boolean changed = false;
1057    ListIterator<E> listIterator = list.listIterator(index);
1058    for (E e : elements) {
1059      listIterator.add(e);
1060      changed = true;
1061    }
1062    return changed;
1063  }
1064
1065  /** An implementation of {@link List#indexOf(Object)}. */
1066  static int indexOfImpl(List<?> list, @Nullable Object element) {
1067    if (list instanceof RandomAccess) {
1068      return indexOfRandomAccess(list, element);
1069    } else {
1070      ListIterator<?> listIterator = list.listIterator();
1071      while (listIterator.hasNext()) {
1072        if (Objects.equal(element, listIterator.next())) {
1073          return listIterator.previousIndex();
1074        }
1075      }
1076      return -1;
1077    }
1078  }
1079
1080  private static int indexOfRandomAccess(List<?> list, @Nullable Object element) {
1081    int size = list.size();
1082    if (element == null) {
1083      for (int i = 0; i < size; i++) {
1084        if (list.get(i) == null) {
1085          return i;
1086        }
1087      }
1088    } else {
1089      for (int i = 0; i < size; i++) {
1090        if (element.equals(list.get(i))) {
1091          return i;
1092        }
1093      }
1094    }
1095    return -1;
1096  }
1097
1098  /** An implementation of {@link List#lastIndexOf(Object)}. */
1099  static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
1100    if (list instanceof RandomAccess) {
1101      return lastIndexOfRandomAccess(list, element);
1102    } else {
1103      ListIterator<?> listIterator = list.listIterator(list.size());
1104      while (listIterator.hasPrevious()) {
1105        if (Objects.equal(element, listIterator.previous())) {
1106          return listIterator.nextIndex();
1107        }
1108      }
1109      return -1;
1110    }
1111  }
1112
1113  private static int lastIndexOfRandomAccess(List<?> list, @Nullable Object element) {
1114    if (element == null) {
1115      for (int i = list.size() - 1; i >= 0; i--) {
1116        if (list.get(i) == null) {
1117          return i;
1118        }
1119      }
1120    } else {
1121      for (int i = list.size() - 1; i >= 0; i--) {
1122        if (element.equals(list.get(i))) {
1123          return i;
1124        }
1125      }
1126    }
1127    return -1;
1128  }
1129
1130  /** Returns an implementation of {@link List#listIterator(int)}. */
1131  static <E extends @Nullable Object> ListIterator<E> listIteratorImpl(List<E> list, int index) {
1132    return new AbstractListWrapper<>(list).listIterator(index);
1133  }
1134
1135  /** An implementation of {@link List#subList(int, int)}. */
1136  static <E extends @Nullable Object> List<E> subListImpl(
1137      final List<E> list, int fromIndex, int toIndex) {
1138    List<E> wrapper;
1139    if (list instanceof RandomAccess) {
1140      wrapper =
1141          new RandomAccessListWrapper<E>(list) {
1142            @Override
1143            public ListIterator<E> listIterator(int index) {
1144              return backingList.listIterator(index);
1145            }
1146
1147            @J2ktIncompatible private static final long serialVersionUID = 0;
1148          };
1149    } else {
1150      wrapper =
1151          new AbstractListWrapper<E>(list) {
1152            @Override
1153            public ListIterator<E> listIterator(int index) {
1154              return backingList.listIterator(index);
1155            }
1156
1157            @J2ktIncompatible private static final long serialVersionUID = 0;
1158          };
1159    }
1160    return wrapper.subList(fromIndex, toIndex);
1161  }
1162
1163  private static class AbstractListWrapper<E extends @Nullable Object> extends AbstractList<E> {
1164    final List<E> backingList;
1165
1166    AbstractListWrapper(List<E> backingList) {
1167      this.backingList = checkNotNull(backingList);
1168    }
1169
1170    @Override
1171    public void add(int index, @ParametricNullness E element) {
1172      backingList.add(index, element);
1173    }
1174
1175    @Override
1176    public boolean addAll(int index, Collection<? extends E> c) {
1177      return backingList.addAll(index, c);
1178    }
1179
1180    @Override
1181    @ParametricNullness
1182    public E get(int index) {
1183      return backingList.get(index);
1184    }
1185
1186    @Override
1187    @ParametricNullness
1188    public E remove(int index) {
1189      return backingList.remove(index);
1190    }
1191
1192    @Override
1193    @ParametricNullness
1194    public E set(int index, @ParametricNullness E element) {
1195      return backingList.set(index, element);
1196    }
1197
1198    @Override
1199    public boolean contains(@Nullable Object o) {
1200      return backingList.contains(o);
1201    }
1202
1203    @Override
1204    public int size() {
1205      return backingList.size();
1206    }
1207  }
1208
1209  private static class RandomAccessListWrapper<E extends @Nullable Object>
1210      extends AbstractListWrapper<E> implements RandomAccess {
1211    RandomAccessListWrapper(List<E> backingList) {
1212      super(backingList);
1213    }
1214  }
1215}