Stream Collectors - toCollection

news/2024/7/8 1:55:21 标签: java

public static <T,​C extends Collection<T>> Collector<T,​?,​C> toCollection​(Supplier<C> collectionFactory)

简述一下就是把集合中的元素转换成参数指定的集合类型进行保存。

看个例子:

void test42() {

        List<Integer> list = List.of(2,5,8,9,4,20,11,43,55);

        ArrayList al = list.stream().collect(Collectors.toCollection(ArrayList::new));

        al.stream().forEach(System.out::print);

    }

运行结果:2589420114355

很容易理解,把List中的数据保存到ArrayList中。再看看方法的定义,​C extends Collection<T>根据这个定义我们可以确定我们可以转换的数据类型范围为所有实现Collection<E>接口的实现类或其子类。如下示例:

RoleList rl = list.stream().collect(Collectors.toCollection(RoleList::new));

HashSet hs = list.stream().collect(Collectors.toCollection(HashSet::new));

你这个时候如果弄个HashMap类型不对肯定报错,或者你弄实现Collection的接口它也new不了所以还是报错。


http://www.niftyadmin.cn/n/928496.html

相关文章

mysql的limit优化

我们工作中可能会遇到大数据量&#xff08;假设上千万条&#xff09;分页的情况&#xff0c;执行的语句类似以下sql语句&#xff1a; select * from record limit 2000000,10 运行这条语句&#xff0c;时间保持在30秒左右&#xff0c;这样的性能是很差的。 那我们该怎么去优化它…

Stream Collectors - toList、toSet

public static <T> Collector<T,​?,​List<T>> toList() public static <T> Collector<T,​?,​Set<T>> toSet() 上面说完了toCollection这里接着说一下toLIst和toSet这两个方法。其实这两个方法的作用toCollection都能实现&#xff…

CentOS 7 安装 Nginx

导语 下面会用 yum 和编译两种方式来安装 Nginx。 yum 安装 使用 yum 命令&#xff0c;是相对简单的&#xff0c;输入 yum install -y nginx 显示如上界面&#xff0c;既是安装成功。接下来开启 Nginx 服务 配置文件在 /etc/nginx/nginx.conf&#xff0c; 代码文件地址在 /usr…

Stream Collectors - toConcurrentMap

和toMap方法一样&#xff0c;也根据参数的不同重载了3个方法&#xff0c;作用也和toMap一样&#xff0c;只不过操作的数据类型是ConcurrentMap&#xff0c;返回结果toMap是HashMap&#xff0c;ConcurrentMap返回的是ConcurrentHashMap&#xff0c;这个执行效率差一点但是是线程…

基于django搭建网站

Django 是由Python开发的一个免费的开源web框架&#xff0c;可以用于快速搭建网站。ps:web框架&#xff0c;也叫web应用框架&#xff0c;提供数据库接口&#xff0c;标准样板&#xff0c;会话管理等来支持网站&#xff0c;网络应用&#xff0c;服务的开发。安装django官网https…

linux--VSS/RSS/PSS/USS

|--内存耗用&#xff1a;VSS/RSS/PSS/USS   VSS - Virtual Set Size 虚拟耗用内存&#xff08;包含共享库占用的内存&#xff09;   RSS - Resident Set Size 实际使用物理内存&#xff08;包含共享库占用的内存&#xff09;   PSS - Proportional Set Size 实际使用的物…

Stream Collectors - toUnmodifiableList、toUnmodifiableSet

public static <T> Collector<T,​?,​List<T>> toUnmodifiableList() public static <T> Collector<T,​?,​Set<T>> toUnmodifiableSet() 根据字面上的意思就是返回的ArrayList或HashSet结果是不可更改的。以上两个方法以toUnmodifi…

[翻译]Effective Java in Kotlin:2. 遇到多个构造器参数时,考虑用构建者

原文&#xff1a;Effective Java in Kotlin, item 2: Consider a builder when faced with many constructor parameters Reminder from the book 在Java中&#xff0c;通常的解决可选构造参数的方式是使用可伸缩构造器&#xff08;telescoping constructor&#xff09;。当使用…