stream流的使用各种记录

记录stream流的使用

List 转成List

我这里获得一串以逗号相隔的字符串,我最后要生成List

c 复制代码
        List<Long> list = Arrays.stream(ids.split(","))
        .map((str) -> Long.parseLong(str))
        .collect(Collectors.toList());

filter相关,筛选数据

c 复制代码
       List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);

        // 遍历输出符合条件的元素
        list.stream().filter(x -> x > 6).forEach(System.out::println);
         // 是否包含符合特定条件的元素
        boolean anyMatch = list.stream().anyMatch(x -> x > 6);

使用filter可以进行筛选

max,min,count

c 复制代码
		List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");

		Optional<String> max = list.stream().max(Comparator.comparing(String::length));

max里边是comparator,比较器,传入一个这个就知道怎么比较辣


c 复制代码
List<Integer> list = Arrays.asList(7, 6, 4, 8, 2, 11, 9);

		long count = list.stream().filter(x -> x > 6).count();
		System.out.println("list中大于6的元素个数:" + count);

统计大于6的个数

map的使用

c 复制代码
String[] strArr = { "abcd", "bcdd", "defde", "fTr" };
List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());

List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
List<Integer> intListNew = intList.stream().map(x -> x + 3).collect(Collectors.toList());

System.out.println("每个元素大写:" + strList);
System.out.println("每个元素+3:" + intListNew);

冷门操作reduce

归纳操作,一般拿来求和 求乘积,求最值

c 复制代码
		List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
		// 求和方式1
		Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
		// 求和方式2
		Optional<Integer> sum2 = list.stream().reduce(Integer::sum);
		// 求和方式3
		Integer sum3 = list.stream().reduce(0, Integer::sum);
		
		// 求乘积
		Optional<Integer> product = list.stream().reduce((x, y) -> x * y);

		// 求最大值方式1
		Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
		// 求最大值写法2
		Integer max2 = list.stream().reduce(1, Integer::max);

		System.out.println("list求和:" + sum.get() + "," + sum2.get() + "," + sum3);
		System.out.println("list求积:" + product.get());
		System.out.println("list求最大值:" + max.get() + "," + max2);
相关推荐
小杜-coding2 小时前
黑马点评day04(分布式锁-setnx)
java·spring boot·redis·分布式·spring·java-ee·mybatis
caihuayuan53 小时前
升级element-ui步骤
java·大数据·spring boot·后端·课程设计
佩奇的技术笔记4 小时前
Java学习手册:单体架构到微服务演进
java·微服务·架构
zm4 小时前
服务器多客户端连接核心要点(1)
java·开发语言
FuckPatience4 小时前
关于C#项目中 服务层使用接口的问题
java·开发语言·c#
天上掉下来个程小白5 小时前
缓存套餐-01.Spring Cache介绍和常用注解
java·redis·spring·缓存·spring cache·苍穹外卖
揣晓丹5 小时前
JAVA实战开源项目:健身房管理系统 (Vue+SpringBoot) 附源码
java·vue.js·spring boot·后端·开源
编程轨迹_5 小时前
使用 Spring 和 Redis 创建处理敏感数据的服务
java·开发语言·restful
奔驰的小野码5 小时前
SpringAI实现AI应用-自定义顾问(Advisor)
java·人工智能·spring boot·spring
奔驰的小野码5 小时前
SpringAI实现AI应用-使用redis持久化聊天记忆
java·数据库·人工智能·redis·spring