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);
相关推荐
SimonKing6 分钟前
颠覆传统IO:零拷贝技术如何重塑Java高性能编程?
java·后端·程序员
sniper_fandc16 分钟前
SpringBoot系列—MyBatis(xml使用)
java·spring boot·mybatis
胚芽鞘6811 小时前
查询依赖冲突工具maven Helper
java·数据库·maven
Charlie__ZS1 小时前
若依框架去掉Redis
java·redis·mybatis
咖啡啡不加糖1 小时前
RabbitMQ 消息队列:从入门到Spring Boot实战
java·spring boot·rabbitmq
玩代码2 小时前
Java线程池原理概述
java·开发语言·线程池
NE_STOP2 小时前
SpringBoot--如何给项目添加配置属性及读取属性
java
水果里面有苹果2 小时前
20-C#构造函数--虚方法
java·前端·c#
%d%d22 小时前
python 在运行时没有加载修改后的版本
java·服务器·python
金銀銅鐵2 小时前
[Kotlin] 单例对象是如何实现的?
java·kotlin