首页 > 其他分享 >Stream toList不能滥用以及与collect(Collectors.toList())的区别

Stream toList不能滥用以及与collect(Collectors.toList())的区别

时间:2024-01-21 13:11:25浏览次数:21  
标签:toList elements Stream Collectors list List code new

Stream toList()返回的是只读List原则上不可修改,collect(Collectors.toList())默认返回的是ArrayList,可以增删改查

1. 背景

在公司看到开发环境突然发现了UnsupportedOperationException 报错,想到了不是自己throw的应该就是操作collection不当。
发现的确是同事使用了类似stringList.stream().filter(number -> Long.parseLong(number) > 1).toList() 以stream.toList()作为返回, 后继续使用了返回值做add操作,导致报错

2. Stream toList()collect(Collectors.toList())的区别

JDK version: 21

IDE: IDEA

从Java16开始,Stream有了直接toList方法, java8时候常用的方法是 stringList.stream().filter(number -> Long.parseLong(number) > 1).collect(Collectors.toList())

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.
     *
     * <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())));
    }

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

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

image


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

        List<String> stringList = List.of("1", "2", "3");
        List<String> largeNumberList = stringList.stream().filter(number -> Long.parseLong(number) > 1).toList();
        List<String> largeNumberList2 = stringList.stream().filter(number -> Long.parseLong(number) > 1).collect(Collectors.toList());
//        largeNumberList.add("4"); //  java.lang.UnsupportedOperationException
        largeNumberList2.add("4"); //success

        // modify custom object attribute
        User userZhang = new User("ZhangSan");
        User userLi = new User("LiSi");
        List<User> userList = List.of(userZhang, userLi);
        List<User> filterList = userList.stream().filter(user -> "LiSi".equals(user.name)).toList();

        User first = filterList.getFirst();//java 21
        first.name = "WangWu";
        filterList.forEach(u -> System.out.println(u.name));
        //List.of返回的也是不能修改的List
        userList.forEach(u -> System.out.print(u.name));

输出结果是:

WangWu

ZhangSanWangWu

Stream collect(Collectors.toList())

返回一个ArrayList 如果没有在toList()方法入参中传入指定Supplier的话, 可以做ArrayList的任何操作

    /**
     * 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
     */
    public static <T>
    Collector<T, ?, List<T>> toList() {
        return new CollectorImpl<>(ArrayList::new, List::add,
                                   (left, right) -> { left.addAll(right); return left; },
                                   CH_ID);
    }

tips: List.of(),返回的也是不可修改的list, an unmodifiable list. 关于 Unmodifiable Lists 说明

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:
They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change.
They disallow null elements. Attempts to create them with null elements result in NullPointerException.
They are serializable if all elements are serializable.
The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
The lists and their subList views implement the RandomAccess interface.
They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
They are serialized as specified on the Serialized Form page.
This interface is a member of the Java Collections Framework.

3.如何使用(不考虑性能)

确定其是一个不再被set/add/remove的list 可使用 Stream toList;
如果使用collect(Collectors.toList()) ,sonar或idea自带以及第三方的一些code checker会爆warning, 以本人经验,可以使用collect(Collectors.toCollection(ArrayList::new))来代替

标签:toList,elements,Stream,Collectors,list,List,code,new
From: https://www.cnblogs.com/jaycezheng/p/17977755

相关文章

  • 无涯教程-Node.js - Streams
    Stream流是使您可以连续地从源读取数据或将数据写入目标的对象,在Node.js中,有四种类型的流-Readable  - 用于读取操作的流。Writable   - 用于写操作的流。Duplex    - 可用于读取和写入操作的流。Transform -一种双工流,其中基于输入来计算输出......
  • Spark Streaming工作原理
         说起SparkStreaming,玩大数据的没有不知道的,但对于小白来说还是有些生疏,所以本篇文章就来介绍一下SparkStreaming,以期让同行能更清楚地掌握SparkStreaming的原理。   一:什么是SparkStreaming   官方对于SparkStreaming的介绍是这样的(翻译过来的):Sp......
  • Flink DataStream API 编程模型
    Flink系列文章第01讲:Flink的应用场景和架构模型第02讲:Flink入门程序WordCount和SQL实现第03讲:Flink的编程模型与其他框架比较第04讲:Flink常用的DataSet和DataStreamAPI第05讲:FlinkSQL&Table编程和案例第06讲:Flink集群安装部署和HA配置第07讲:Flink常见......
  • spark streaming简介
    SparkStreaming用于流式数据处理(准实时,微批次),SparkStreaming支持的数据源很多,例如:kafka、Flume、简单的TCP套接字等,数据输入后可以用Spark的高度抽象原语,如:map、join、reduce、window等进行运算,而结果也可以保存在很多地方,如:hdfs、数据库等。和Spark基于RDD的概念很相似,Spark......
  • Stream (是异步版本的列表)、StreamBuilder(局部数据更新)
    Stream流Stream的字面意思是水流,Stream不像Future那样只会在未来获取一个值,它可以异步获取0个或者多个值。如果说Future是一个异步版本的int或者String,Stream则更像是异步版本的列表,List,List,列表里面可能会有0个或者多个元素。classMyHomePageextendsStatefulWidget{......
  • Gstreamer Rtspsrc连接大华摄像头失败原因及解决
    先说解决办法sudoapt-getremovegstreamer1.0-plugins-ugly分析过程和原因输入命令gst-launch-1.0rtspsrclocation="rtsp/url"!fakesink终端输出如下SettingpipelinetoPAUSED...PipelineisliveanddoesnotneedPREROLL...Progress:(open)OpeningStre......
  • SparkStreaming 连接 Kafka数据源
    本文的前提条件:SparkStreaminginJava参考地址:SparkStreaming+KafkaIntegrationGuide(Kafkabrokerversion0.10.0orhigher)1.添加POM依赖<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>......
  • Stream API
    StreamAPI概念:StreamAPI是Java8中处理集合的关键抽象概念,StreamAPI允许开发人员在不改变原始数据源的情况下对集合进行操作(查找、过滤、数据映射等等),这使得代码更加简洁、易读和可维护。总之,StreamAPI提供了一种高效且易于使用的数据处理方式注意点:Stream不会存储数据......
  • SparkStreaming 自定义数据采集器
    本文的前提条件:SparkStreaminginJava参考地址:SparkStreamingCustomReceivers1.自定义数据采集器packagecn.coreqi.receiver;importorg.apache.spark.storage.StorageLevel;importorg.apache.spark.streaming.receiver.Receiver;importjava.util.Random;/**......
  • SparkStreaming in Java
    参考地址:SparkStreamingProgrammingGuide1.新建Maven项目,POM引入依赖<dependency><groupId>org.apache.spark</groupId><artifactId>spark-streaming_2.13</artifactId><version>3.5.0</ve......