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