stream流的基本使用

本文章已经生成可运行项目,

1.概念

stream流可以理解为一个处理集合的流水线。在流水线上可以对集合的数据进行任意的加工,直到流水线执行完毕这个流也算结束。对流进行处理的时候不会改变原来的集合的值,相当于复制一个集合拿来上流水线操作。流水线开始就是.stream(),结束一般使用.collect(Collectors.toList())。

2.常用方法

1.filter过滤,给一个判断条件,留下符合条件的

// 过滤集合中的空字符串
List<String> list = Arrays.asList("123", "456", "789",""," ");
List<String> collect = list.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
collect : [123, 456, 789]

2.map,给一个方法,每一个参数都会执行一下这个方法

// 给每一个字符串前面加一个"new"
List<String> list = Arrays.asList("123", "456", "789",""," ");
List<String> collect = list.stream().map(s -> "new" + s).collect(Collectors.toList());
collect : [new123, new456, new789, new, new ]

3.allMatch : 全部符合条件,anyMatch : 只要存在符合条件的,noneMatch : 不存在符合条件的

List<Integer> list = Arrays.asList(10,12,14,15);
// 集合中是否全是偶数
boolean b = list.stream().allMatch(n -> n % 2 == 0);
b : false
// 集合中是否含有偶数
boolean b = list.stream().anyMatch(n -> n % 2 == 0);
b : true
// 集合中不存在偶数
boolean b = list.stream().noneMatch(n -> n % 2 == 0);
b : false

4.sorted排序

List<Integer> list = Arrays.asList(1,32,12,12,42,9);
// 正排
List<Integer> collect = list.stream().sorted().collect(Collectors.toList());
// 倒排
List<Integer> collect1 = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

5.reduce元素归一

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
// 元素累加
Integer sum = list.stream().reduce(0, (a, b) -> a + b);
sum : 55
// 元素最大值
AtomicReference<Integer> maxNum = new AtomicReference<>();
list.stream().reduce(Integer::max).ifPresent(n -> maxNum.set(n));
maxNum : 10

6.其他方法

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,7,8,9,10);
// 去重
List<Integer> collect = list.stream().distinct().collect(Collectors.toList());
collect : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// 计数
Long count = list.stream().count();
count : 14
// 取前5个值
List<Integer> collect = list.stream().limit(5).collect(Collectors.toList());
collect : [1, 2, 3, 4, 5]
// 跳过前10个值
List<Integer> collect = list.stream().skip(10).collect(Collectors.toList());
collect : [7, 8, 9, 10]

3.注意事项

1.使用toMap

转为map的时候如果key有重复值会报错,解决方法就是使用第三个参数(oldValue, newValue) -> newValue),遇到重复key值时,使用新value替换旧value

User user = User.builder().id("123").name("张三").build();
User user1 = User.builder().id("123").name("张四").build();
User user2 = User.builder().id("1234").name("王五").build();
List<User> userList = Arrays.asList(user,user1,user2);
// 转为map
Map<String, String> userMap = userList.stream()
        .collect(Collectors.toMap(
                User::getId,
                User::getName,
                (oldValue, newValue) -> newValue)
         );        
userMap : {123=张四, 1234=王五}

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值