专栏名称: ImportNew
伯乐在线旗下账号,专注Java技术分享,包括Java基础技术、进阶技能、架构设计和Java技术领域动态等。
目录
相关文章推荐
51好读  ›  专栏  ›  ImportNew

千万不要滥用Stream.toList(),有坑!

ImportNew  · 公众号  · Java  · 2024-03-16 10:06

正文

请到「今天看啥」查看全文


Stream toList()

/**
 * 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.
 *
 * 

The returned instance may be value-based.
 * 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.
 *
 * 

This is a terminal operation.
 *
 * @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:
 * 

{@code
 * Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray())))
 * }

 *
 * @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 toList() {
    return (List) Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray())));
}

查看源码 Stream toList调用的是 Collections.unmodifiableList 而在 unmodifiableList(List extends T> list) 实现中, 都会返回一个不可修改的List,所以不能使用set/add/remove等改变list数组的方法。

 return (list instanceof RandomAccess ?
        new UnmodifiableRandomAccessList<>(list) :
        new UnmodifiableList<>(list));

图片

但其实也可以修改List的元素的某些属性,例如







请到「今天看啥」查看全文