Class Lists

java.lang.Object
com.google.common.collect.Lists

@GwtCompatible(emulated=true) public final class Lists extends Object
Static utility methods pertaining to List instances. Also see this class's counterparts Sets, Maps and Queues.

See the Guava User Guide article on Lists.

Since:
2.0
Author:
Kevin Bourrillion, Mike Bostock, Louis Wasserman
  • Method Details

    • newArrayList

      @GwtCompatible(serializable=true) public static <E extends @Nullable Object> ArrayList<E> newArrayList()
      Creates a mutable, empty ArrayList instance (for Java 6 and earlier).

      Note: if mutability is not required, use ImmutableList.of() instead.

      Note: this method is now unnecessary and should be treated as deprecated. Instead, use the ArrayList constructor directly, taking advantage of "diamond" syntax.

    • newArrayList

      @SafeVarargs @GwtCompatible(serializable=true) public static <E extends @Nullable Object> ArrayList<E> newArrayList(E... elements)
      Creates a mutable ArrayList instance containing the given elements.

      Note: essentially the only reason to use this method is when you will need to add or remove elements later. Otherwise, for non-null elements use ImmutableList.of() (for varargs) or ImmutableList.copyOf(Object[]) (for an array) instead. If any elements might be null, or you need support for List.set(int, Object), use Arrays.asList(T...).

      Note that even when you do need the ability to add or remove, this method provides only a tiny bit of syntactic sugar for newArrayList(asList (...)), or for creating an empty list then calling Collections.addAll(java.util.Collection<? super T>, T...). This method is not actually very useful and will likely be deprecated in the future.

    • newArrayList

      @GwtCompatible(serializable=true) public static <E extends @Nullable Object> ArrayList<E> newArrayList(Iterable<? extends E> elements)
      Creates a mutable ArrayList instance containing the given elements; a very thin shortcut for creating an empty list then calling Iterables.addAll(java.util.Collection<T>, java.lang.Iterable<? extends T>).

      Note: if mutability is not required and the elements are non-null, use ImmutableList.copyOf(Iterable) instead. (Or, change elements to be a FluentIterable and call elements.toList().)

      Note: if elements is a Collection, you don't need this method. Use the ArrayList constructor directly, taking advantage of "diamond" syntax.

    • newArrayList

      @GwtCompatible(serializable=true) public static <E extends @Nullable Object> ArrayList<E> newArrayList(Iterator<? extends E> elements)
      Creates a mutable ArrayList instance containing the given elements; a very thin shortcut for creating an empty list and then calling Iterators.addAll(java.util.Collection<T>, java.util.Iterator<? extends T>).

      Note: if mutability is not required and the elements are non-null, use ImmutableList.copyOf(Iterator) instead.

    • newArrayListWithCapacity

      @GwtCompatible(serializable=true) public static <E extends @Nullable Object> ArrayList<E> newArrayListWithCapacity(int initialArraySize)
      Creates an ArrayList instance backed by an array with the specified initial size; simply delegates to ArrayList(int).

      Note: this method is now unnecessary and should be treated as deprecated. Instead, use new ArrayList<>(int) directly, taking advantage of "diamond" syntax. (Unlike here, there is no risk of overload ambiguity, since the ArrayList constructors very wisely did not accept varargs.)

      Parameters:
      initialArraySize - the exact size of the initial backing array for the returned array list (ArrayList documentation calls this value the "capacity")
      Returns:
      a new, empty ArrayList which is guaranteed not to resize itself unless its size reaches initialArraySize + 1
      Throws:
      IllegalArgumentException - if initialArraySize is negative
    • newArrayListWithExpectedSize

      @GwtCompatible(serializable=true) public static <E extends @Nullable Object> ArrayList<E> newArrayListWithExpectedSize(int estimatedSize)
      Creates an ArrayList instance to hold estimatedSize elements, plus an unspecified amount of padding; you almost certainly mean to call newArrayListWithCapacity(int) (see that method for further advice on usage).

      Note: This method will soon be deprecated. Even in the rare case that you do want some amount of padding, it's best if you choose your desired amount explicitly.

      Parameters:
      estimatedSize - an estimate of the eventual List.size() of the new list
      Returns:
      a new, empty ArrayList, sized appropriately to hold the estimated number of elements
      Throws:
      IllegalArgumentException - if estimatedSize is negative
    • newLinkedList

      @GwtCompatible(serializable=true) public static <E extends @Nullable Object> LinkedList<E> newLinkedList()
      Creates a mutable, empty LinkedList instance (for Java 6 and earlier).

      Note: if you won't be adding any elements to the list, use ImmutableList.of() instead.

      Performance note: ArrayList and ArrayDeque consistently outperform LinkedList except in certain rare and specific situations. Unless you have spent a lot of time benchmarking your specific needs, use one of those instead.

      Note: this method is now unnecessary and should be treated as deprecated. Instead, use the LinkedList constructor directly, taking advantage of "diamond" syntax.

    • newLinkedList

      @GwtCompatible(serializable=true) public static <E extends @Nullable Object> LinkedList<E> newLinkedList(Iterable<? extends E> elements)
      Creates a mutable LinkedList instance containing the given elements; a very thin shortcut for creating an empty list then calling Iterables.addAll(java.util.Collection<T>, java.lang.Iterable<? extends T>).

      Note: if mutability is not required and the elements are non-null, use ImmutableList.copyOf(Iterable) instead. (Or, change elements to be a FluentIterable and call elements.toList().)

      Performance note: ArrayList and ArrayDeque consistently outperform LinkedList except in certain rare and specific situations. Unless you have spent a lot of time benchmarking your specific needs, use one of those instead.

      Note: if elements is a Collection, you don't need this method. Use the LinkedList constructor directly, taking advantage of "diamond" syntax.

    • newCopyOnWriteArrayList

      Creates an empty CopyOnWriteArrayList instance.

      Note: if you need an immutable empty List, use Collections.emptyList() instead.

      Returns:
      a new, empty CopyOnWriteArrayList
      Since:
      12.0
    • newCopyOnWriteArrayList

      @GwtIncompatible public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(Iterable<? extends E> elements)
      Creates a CopyOnWriteArrayList instance containing the given elements.
      Parameters:
      elements - the elements that the list should contain, in order
      Returns:
      a new CopyOnWriteArrayList containing those elements
      Since:
      12.0
    • asList

      public static <E extends @Nullable Object> List<E> asList(E first, E[] rest)
      Returns an unmodifiable list containing the specified first element and backed by the specified array of additional elements. Changes to the rest array will be reflected in the returned list. Unlike Arrays.asList(T...), the returned list is unmodifiable.

      This is useful when a varargs method needs to use a signature such as (Foo firstFoo, Foo... moreFoos), in order to avoid overload ambiguity or to enforce a minimum argument count.

      The returned list is serializable and implements RandomAccess.

      Parameters:
      first - the first element
      rest - an array of additional elements, possibly empty
      Returns:
      an unmodifiable list containing the specified elements
    • asList

      public static <E extends @Nullable Object> List<E> asList(E first, E second, E[] rest)
      Returns an unmodifiable list containing the specified first and second element, and backed by the specified array of additional elements. Changes to the rest array will be reflected in the returned list. Unlike Arrays.asList(T...), the returned list is unmodifiable.

      This is useful when a varargs method needs to use a signature such as (Foo firstFoo, Foo secondFoo, Foo... moreFoos), in order to avoid overload ambiguity or to enforce a minimum argument count.

      The returned list is serializable and implements RandomAccess.

      Parameters:
      first - the first element
      second - the second element
      rest - an array of additional elements, possibly empty
      Returns:
      an unmodifiable list containing the specified elements
    • cartesianProduct

      public static <B> List<List<B>> cartesianProduct(List<? extends List<? extends B>> lists)
      Returns every possible list that can be formed by choosing one element from each of the given lists in order; the "n-ary Cartesian product" of the lists. For example:
      
       Lists.cartesianProduct(ImmutableList.of(
           ImmutableList.of(1, 2),
           ImmutableList.of("A", "B", "C")))
       

      returns a list containing six lists in the following order:

      • ImmutableList.of(1, "A")
      • ImmutableList.of(1, "B")
      • ImmutableList.of(1, "C")
      • ImmutableList.of(2, "A")
      • ImmutableList.of(2, "B")
      • ImmutableList.of(2, "C")

      The result is guaranteed to be in the "traditional", lexicographical order for Cartesian products that you would get from nesting for loops:

      
       for (B b0 : lists.get(0)) {
         for (B b1 : lists.get(1)) {
           ...
           ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
           // operate on tuple
         }
       }
       

      Note that if any input list is empty, the Cartesian product will also be empty. If no lists at all are provided (an empty list), the resulting Cartesian product has one element, an empty list (counter-intuitive, but mathematically consistent).

      Performance notes: while the cartesian product of lists of size m, n, p is a list of size m x n x p, its actual memory consumption is much smaller. When the cartesian product is constructed, the input lists are merely copied. Only as the resulting list is iterated are the individual lists created, and these are not retained after iteration.

      Type Parameters:
      B - any common base class shared by all axes (often just Object)
      Parameters:
      lists - the lists to choose elements from, in the order that the elements chosen from those lists should appear in the resulting lists
      Returns:
      the Cartesian product, as an immutable list containing immutable lists
      Throws:
      IllegalArgumentException - if the size of the cartesian product would be greater than Integer.MAX_VALUE
      NullPointerException - if lists, any one of the lists, or any element of a provided list is null
      Since:
      19.0
    • cartesianProduct

      @SafeVarargs public static <B> List<List<B>> cartesianProduct(List<? extends B>... lists)
      Returns every possible list that can be formed by choosing one element from each of the given lists in order; the "n-ary Cartesian product" of the lists. For example:
      
       Lists.cartesianProduct(ImmutableList.of(
           ImmutableList.of(1, 2),
           ImmutableList.of("A", "B", "C")))
       

      returns a list containing six lists in the following order:

      • ImmutableList.of(1, "A")
      • ImmutableList.of(1, "B")
      • ImmutableList.of(1, "C")
      • ImmutableList.of(2, "A")
      • ImmutableList.of(2, "B")
      • ImmutableList.of(2, "C")

      The result is guaranteed to be in the "traditional", lexicographical order for Cartesian products that you would get from nesting for loops:

      
       for (B b0 : lists.get(0)) {
         for (B b1 : lists.get(1)) {
           ...
           ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
           // operate on tuple
         }
       }
       

      Note that if any input list is empty, the Cartesian product will also be empty. If no lists at all are provided (an empty list), the resulting Cartesian product has one element, an empty list (counter-intuitive, but mathematically consistent).

      Performance notes: while the cartesian product of lists of size m, n, p is a list of size m x n x p, its actual memory consumption is much smaller. When the cartesian product is constructed, the input lists are merely copied. Only as the resulting list is iterated are the individual lists created, and these are not retained after iteration.

      Type Parameters:
      B - any common base class shared by all axes (often just Object)
      Parameters:
      lists - the lists to choose elements from, in the order that the elements chosen from those lists should appear in the resulting lists
      Returns:
      the Cartesian product, as an immutable list containing immutable lists
      Throws:
      IllegalArgumentException - if the size of the cartesian product would be greater than Integer.MAX_VALUE
      NullPointerException - if lists, any one of the lists, or any element of a provided list is null
      Since:
      19.0
    • transform

      public static <F extends @Nullable Object, T extends @Nullable Object> List<T> transform(List<F> fromList, Function<? super F,? extends T> function)
      Returns a list that applies function to each element of fromList. The returned list is a transformed view of fromList; changes to fromList will be reflected in the returned list and vice versa.

      Since functions are not reversible, the transform is one-way and new items cannot be stored in the returned list. The add, addAll and set methods are unsupported in the returned list.

      The function is applied lazily, invoked when needed. This is necessary for the returned list to be a view, but it means that the function will be applied many times for bulk operations like List.contains(java.lang.Object) and List.hashCode(). For this to perform well, function should be fast. To avoid lazy evaluation when the returned list doesn't need to be a view, copy the returned list into a new list of your choosing.

      If fromList implements RandomAccess, so will the returned list. The returned list is threadsafe if the supplied list and function are.

      If only a Collection or Iterable input is available, use Collections2.transform(java.util.Collection<F>, com.google.common.base.Function<? super F, T>) or Iterables.transform(java.lang.Iterable<F>, com.google.common.base.Function<? super F, ? extends T>).

      Note: serializing the returned list is implemented by serializing fromList, its contents, and function -- not by serializing the transformed values. This can lead to surprising behavior, so serializing the returned list is not recommended. Instead, copy the list using ImmutableList.copyOf(Collection) (for example), then serialize the copy. Other methods similar to this do not implement serialization at all for this reason.

      Java 8+ users: many use cases for this method are better addressed by Stream.map(java.util.function.Function<? super T, ? extends R>). This method is not being deprecated, but we gently encourage you to migrate to streams.

    • partition

      public static <T extends @Nullable Object> List<List<T>> partition(List<T> list, int size)
      Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer list containing two inner lists of three and two elements, all in the original order.

      The outer list is unmodifiable, but reflects the latest state of the source list. The inner lists are sublist views of the original list, produced on demand using List.subList(int, int), and are subject to all the usual caveats about modification as explained in that API.

      Parameters:
      list - the list to return consecutive sublists of
      size - the desired size of each sublist (the last may be smaller)
      Returns:
      a list of consecutive sublists
      Throws:
      IllegalArgumentException - if partitionSize is nonpositive
    • charactersOf

      public static ImmutableList<Character> charactersOf(String string)
      Returns a view of the specified string as an immutable list of Character values.
      Since:
      7.0
    • charactersOf

      public static List<Character> charactersOf(CharSequence sequence)
      Returns a view of the specified CharSequence as a List<Character>, viewing sequence as a sequence of Unicode code units. The view does not support any modification operations, but reflects any changes to the underlying character sequence.
      Parameters:
      sequence - the character sequence to view as a List of characters
      Returns:
      an List<Character> view of the character sequence
      Since:
      7.0
    • reverse

      public static <T extends @Nullable Object> List<T> reverse(List<T> list)
      Returns a reversed view of the specified list. For example, Lists.reverse(Arrays.asList(1, 2, 3)) returns a list containing 3, 2, 1. The returned list is backed by this list, so changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

      The returned list is random-access if the specified list is random access.

      Since:
      7.0