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