Class Lists
- java.lang.Object
-
- com.google.common.collect.Lists
-
@GwtCompatible(emulated=true) public final class Lists extends java.lang.Object
Static utility methods pertaining toList
instances. Also see this class's counterpartsSets
,Maps
andQueues
.See the Guava User Guide article on
Lists
.- Since:
- 2.0
- Author:
- Kevin Bourrillion, Mike Bostock, Louis Wasserman
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <E extends @Nullable java.lang.Object>
java.util.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.static <E extends @Nullable java.lang.Object>
java.util.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.static <B> java.util.List<java.util.List<B>>
cartesianProduct(java.util.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.static <B> java.util.List<java.util.List<B>>
cartesianProduct(java.util.List<? extends java.util.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.static java.util.List<java.lang.Character>
charactersOf(java.lang.CharSequence sequence)
Returns a view of the specifiedCharSequence
as aList<Character>
, viewingsequence
as a sequence of Unicode code units.static ImmutableList<java.lang.Character>
charactersOf(java.lang.String string)
Returns a view of the specified string as an immutable list ofCharacter
values.static <E extends @Nullable java.lang.Object>
java.util.ArrayList<E>newArrayList()
Creates a mutable, emptyArrayList
instance (for Java 6 and earlier).static <E extends @Nullable java.lang.Object>
java.util.ArrayList<E>newArrayList(E... elements)
Creates a mutableArrayList
instance containing the given elements.static <E extends @Nullable java.lang.Object>
java.util.ArrayList<E>newArrayList(java.lang.Iterable<? extends E> elements)
Creates a mutableArrayList
instance containing the given elements; a very thin shortcut for creating an empty list then callingIterables.addAll(java.util.Collection<T>, java.lang.Iterable<? extends T>)
.static <E extends @Nullable java.lang.Object>
java.util.ArrayList<E>newArrayList(java.util.Iterator<? extends E> elements)
Creates a mutableArrayList
instance containing the given elements; a very thin shortcut for creating an empty list and then callingIterators.addAll(java.util.Collection<T>, java.util.Iterator<? extends T>)
.static <E extends @Nullable java.lang.Object>
java.util.ArrayList<E>newArrayListWithCapacity(int initialArraySize)
Creates anArrayList
instance backed by an array with the specified initial size; simply delegates toArrayList(int)
.static <E extends @Nullable java.lang.Object>
java.util.ArrayList<E>newArrayListWithExpectedSize(int estimatedSize)
Creates anArrayList
instance to holdestimatedSize
elements, plus an unspecified amount of padding; you almost certainly mean to callnewArrayListWithCapacity(int)
(see that method for further advice on usage).static <E extends @Nullable java.lang.Object>
java.util.concurrent.CopyOnWriteArrayList<E>newCopyOnWriteArrayList()
Creates an emptyCopyOnWriteArrayList
instance.static <E extends @Nullable java.lang.Object>
java.util.concurrent.CopyOnWriteArrayList<E>newCopyOnWriteArrayList(java.lang.Iterable<? extends E> elements)
Creates aCopyOnWriteArrayList
instance containing the given elements.static <E extends @Nullable java.lang.Object>
java.util.LinkedList<E>newLinkedList()
Creates a mutable, emptyLinkedList
instance (for Java 6 and earlier).static <E extends @Nullable java.lang.Object>
java.util.LinkedList<E>newLinkedList(java.lang.Iterable<? extends E> elements)
Creates a mutableLinkedList
instance containing the given elements; a very thin shortcut for creating an empty list then callingIterables.addAll(java.util.Collection<T>, java.lang.Iterable<? extends T>)
.static <T extends @Nullable java.lang.Object>
java.util.List<java.util.List<T>>partition(java.util.List<T> list, int size)
Returns consecutive sublists of a list, each of the same size (the final list may be smaller).static <T extends @Nullable java.lang.Object>
java.util.List<T>reverse(java.util.List<T> list)
Returns a reversed view of the specified list.static <F extends @Nullable java.lang.Object,T extends @Nullable java.lang.Object>
java.util.List<T>transform(java.util.List<F> fromList, Function<? super F,? extends T> function)
Returns a list that appliesfunction
to each element offromList
.
-
-
-
Method Detail
-
newArrayList
@GwtCompatible(serializable=true) public static <E extends @Nullable java.lang.Object> java.util.ArrayList<E> newArrayList()
Creates a mutable, emptyArrayList
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 java.lang.Object> java.util.ArrayList<E> newArrayList(E... elements)
Creates a mutableArrayList
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) orImmutableList.copyOf(Object[])
(for an array) instead. If any elements might be null, or you need support forList.set(int, Object)
, useArrays.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 callingCollections.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 java.lang.Object> java.util.ArrayList<E> newArrayList(java.lang.Iterable<? extends E> elements)
Creates a mutableArrayList
instance containing the given elements; a very thin shortcut for creating an empty list then callingIterables.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, changeelements
to be aFluentIterable
and callelements.toList()
.)Note: if
elements
is aCollection
, you don't need this method. Use theArrayList
constructor directly, taking advantage of "diamond" syntax.
-
newArrayList
@GwtCompatible(serializable=true) public static <E extends @Nullable java.lang.Object> java.util.ArrayList<E> newArrayList(java.util.Iterator<? extends E> elements)
Creates a mutableArrayList
instance containing the given elements; a very thin shortcut for creating an empty list and then callingIterators.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 java.lang.Object> java.util.ArrayList<E> newArrayListWithCapacity(int initialArraySize)
Creates anArrayList
instance backed by an array with the specified initial size; simply delegates toArrayList(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 theArrayList
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 reachesinitialArraySize + 1
- Throws:
java.lang.IllegalArgumentException
- ifinitialArraySize
is negative
-
newArrayListWithExpectedSize
@GwtCompatible(serializable=true) public static <E extends @Nullable java.lang.Object> java.util.ArrayList<E> newArrayListWithExpectedSize(int estimatedSize)
Creates anArrayList
instance to holdestimatedSize
elements, plus an unspecified amount of padding; you almost certainly mean to callnewArrayListWithCapacity(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 eventualList.size()
of the new list- Returns:
- a new, empty
ArrayList
, sized appropriately to hold the estimated number of elements - Throws:
java.lang.IllegalArgumentException
- ifestimatedSize
is negative
-
newLinkedList
@GwtCompatible(serializable=true) public static <E extends @Nullable java.lang.Object> java.util.LinkedList<E> newLinkedList()
Creates a mutable, emptyLinkedList
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
andArrayDeque
consistently outperformLinkedList
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 java.lang.Object> java.util.LinkedList<E> newLinkedList(java.lang.Iterable<? extends E> elements)
Creates a mutableLinkedList
instance containing the given elements; a very thin shortcut for creating an empty list then callingIterables.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, changeelements
to be aFluentIterable
and callelements.toList()
.)Performance note:
ArrayList
andArrayDeque
consistently outperformLinkedList
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 aCollection
, you don't need this method. Use theLinkedList
constructor directly, taking advantage of "diamond" syntax.
-
newCopyOnWriteArrayList
@GwtIncompatible public static <E extends @Nullable java.lang.Object> java.util.concurrent.CopyOnWriteArrayList<E> newCopyOnWriteArrayList()
Creates an emptyCopyOnWriteArrayList
instance.Note: if you need an immutable empty
List
, useCollections.emptyList()
instead.- Returns:
- a new, empty
CopyOnWriteArrayList
- Since:
- 12.0
-
newCopyOnWriteArrayList
@GwtIncompatible public static <E extends @Nullable java.lang.Object> java.util.concurrent.CopyOnWriteArrayList<E> newCopyOnWriteArrayList(java.lang.Iterable<? extends E> elements)
Creates aCopyOnWriteArrayList
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 java.lang.Object> java.util.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 therest
array will be reflected in the returned list. UnlikeArrays.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 elementrest
- an array of additional elements, possibly empty- Returns:
- an unmodifiable list containing the specified elements
-
asList
public static <E extends @Nullable java.lang.Object> java.util.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 therest
array will be reflected in the returned list. UnlikeArrays.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 elementsecond
- the second elementrest
- an array of additional elements, possibly empty- Returns:
- an unmodifiable list containing the specified elements
-
cartesianProduct
public static <B> java.util.List<java.util.List<B>> cartesianProduct(java.util.List<? extends java.util.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 sizem 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 justObject
)- 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:
java.lang.IllegalArgumentException
- if the size of the cartesian product would be greater thanInteger.MAX_VALUE
java.lang.NullPointerException
- iflists
, any one of thelists
, or any element of a provided list is null- Since:
- 19.0
-
cartesianProduct
@SafeVarargs public static <B> java.util.List<java.util.List<B>> cartesianProduct(java.util.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 sizem 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 justObject
)- 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:
java.lang.IllegalArgumentException
- if the size of the cartesian product would be greater thanInteger.MAX_VALUE
java.lang.NullPointerException
- iflists
, any one of thelists
, or any element of a provided list is null- Since:
- 19.0
-
transform
public static <F extends @Nullable java.lang.Object,T extends @Nullable java.lang.Object> java.util.List<T> transform(java.util.List<F> fromList, Function<? super F,? extends T> function)
Returns a list that appliesfunction
to each element offromList
. The returned list is a transformed view offromList
; changes tofromList
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
andset
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)
andList.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
implementsRandomAccess
, so will the returned list. The returned list is threadsafe if the supplied list and function are.If only a
Collection
orIterable
input is available, useCollections2.transform(java.util.Collection<F>, com.google.common.base.Function<? super F, T>)
orIterables.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, andfunction
-- not by serializing the transformed values. This can lead to surprising behavior, so serializing the returned list is not recommended. Instead, copy the list usingImmutableList.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 java.lang.Object> java.util.List<java.util.List<T>> partition(java.util.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 ofsize
- the desired size of each sublist (the last may be smaller)- Returns:
- a list of consecutive sublists
- Throws:
java.lang.IllegalArgumentException
- ifpartitionSize
is nonpositive
-
charactersOf
public static ImmutableList<java.lang.Character> charactersOf(java.lang.String string)
Returns a view of the specified string as an immutable list ofCharacter
values.- Since:
- 7.0
-
charactersOf
public static java.util.List<java.lang.Character> charactersOf(java.lang.CharSequence sequence)
Returns a view of the specifiedCharSequence
as aList<Character>
, viewingsequence
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 aList
of characters- Returns:
- an
List<Character>
view of the character sequence - Since:
- 7.0
-
reverse
public static <T extends @Nullable java.lang.Object> java.util.List<T> reverse(java.util.List<T> list)
Returns a reversed view of the specified list. For example,Lists.reverse(Arrays.asList(1, 2, 3))
returns a list containing3, 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
-
-