/** * Accumulates the elements of this stream into a {@code List}. The elements in * the list will be in this stream's encounter order, if one exists. The returned List * is unmodifiable; calls to any mutator method will always cause * {@code UnsupportedOperationException} to be thrown. There are no * guarantees on the implementation type or serializability of the returned List. * * <p>The returned instance may be <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>. * Callers should make no assumptions about the identity of the returned instances. * Identity-sensitive operations on these instances (reference equality ({@code ==}), * identity hash code, and synchronization) are unreliable and should be avoided. * * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. * * @apiNote If more control over the returned object is required, use * {@link Collectors#toCollection(Supplier)}. * * @implSpec The implementation in this interface returns a List produced as if by the following: * <pre>{@code * Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray()))) * }</pre> * * @implNote Most instances of Stream will override this method and provide an implementation * that is highly optimized compared to the implementation in this interface. * * @return a List containing the stream elements * * @since 16 */ @SuppressWarnings("unchecked") default List<T> toList(){ return (List<T>) Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray()))); }
/** * Returns a {@code Collector} that accumulates the input elements into a * new {@code List}. There are no guarantees on the type, mutability, * serializability, or thread-safety of the {@code List} returned; if more * control over the returned {@code List} is required, use {@link #toCollection(Supplier)}. * * @param <T> the type of the input elements * @return a {@code Collector} which collects all the input elements into a * {@code List}, in encounter order */ publicstatic <T> Collector<T, ?, List<T>> toList() { returnnew CollectorImpl<>(ArrayList::new, List::add, (left, right) -> { left.addAll(right); return left; }, CH_ID); }
tips: List.of(),返回的也是不可修改的list, an unmodifiable list. 关于 Unmodifiable Lists 说明