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