Java8如何从一个Stream中过滤null值
作者:wangmm0218 时间:2022-02-03 08:10:20
从一个Stream中过滤null值
复习一个Stream 包含 null 数据的例子.
Java8Examples.java
package com.mkyong.java8;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8Examples {
public static void main(String[] args) {
Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php");
List<String> result = language.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
output
java
python
node
null // <--- NULL
ruby
null // <--- NULL
php
Solution(解决)
为了解决上面的问题,我们使用: Stream.filter(x -> x!=null)
Java8Examples.java
package com.mkyong.java8;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8Examples {
public static void main(String[] args) {
Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php");
//List<String> result = language.collect(Collectors.toList());
List<String> result = language.filter(x -> x!=null).collect(Collectors.toList());
result.forEach(System.out::println);
}
}
output
java
python
node
ruby
php
另外,过滤器还可以用: Objects::nonNull
import java.util.List;
List<String> result = language.filter(Objects::nonNull).collect(Collectors.toList());
stream方法过滤条件的使用
@Data
@AllArgsConstructor
public class User {
private Long id; // id
private Integer age; // 年龄
private Byte gentle; // 性别
private String name; // 名字
private Integer rank; // 排名
}
User user0 = new User(1L, 18, (byte) 0, "张三", 1);
User user1 = new User(2L, 20, (byte) 1, "李四", 4);
User user2 = new User(3L, 35, (byte) 0, "王五", 2);
User user3 = new User(4L, 29, (byte) 1, "赵六", 3);
下面以List为例
实际上只要是Collection的子类,玩法都类似
1、生成stream
List<User> list = Arrays.asList(user0, user1, user2, user3);
Stream<User> stream = null;
stream = list.stream(); // 需要预判NPE
stream = Optional.of(list).orElseGet(Collections::emptyList).stream(); // 需要预判NPE
stream = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream();
stream = Optional.ofNullable(list).orElseGet(Collections::emptyList).parallelStream(); // 并行处理流
stream = Stream.of(user0, user1, user2, user3).parallel(); // 直接构造
stream = Stream.of(Arrays.asList(user0, user1), Arrays.asList(user2, user3)).flatMap(Collection::stream); // flatMap合并
2、stream操作
// 过滤出性别为0的user
List<User> userList = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().filter(user -> (byte) 0 == user.getGentle()).collect(Collectors.toList());
// 获取排名大于1的用户年龄set
Set<Integer> ageList = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().filter(user -> 1 < user.getRank()).map(User::getAge).collect(Collectors.toSet());
// 合计性别为0的user的年龄
Integer totalAge = Optional.ofNullable(userList).orElseGet(Collections::emptyList).stream().map(User::getAge).reduce(0, Integer::sum);
// 按排名倒序排列
List<User> sortedUserList = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().sorted(Comparator.comparing(User::getRank, Comparator.reverseOrder())).collect(Collectors.toList());
// 获取排名第2高的user
User rankUser = Optional.ofNullable(sortedUserList).orElseGet(Collections::emptyList).stream().skip(1).findFirst().get();
// 排名最高的user
User highestRankUser = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().max(Comparator.comparing(User::getRank)).get();
// 是否存在排名大于1的user
boolean flag = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().anyMatch(user -> user.getRank() > 1);
// 是否所有user排名都大于1
boolean flag = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().allMatch(user -> user.getRank() > 1);
// 是否所有user排名都不大于5
boolean flag = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().noneMatch(user -> user.getRank() > 5);
// 按唯一id分组
Map<Long, User> idUserMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.toMap(User::getId, Function.identity()));
// 按唯一id,名字分组
Map<Long, String> idNameMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.toMap(User::getId, User::getName));
// 按年龄,名字分组,相同年龄的后出现的被覆盖
Map<Integer, String> ageNameMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.toMap(User::getAge, User::getName, (a, b) -> a));
// 按性别分组
Map<Byte, List<User>> gentleUserMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.groupingBy(User::getGentle));
// 按排名是否大于3分组
Map<Boolean, List<User>> partitionUserMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.partitioningBy(user -> user.getRank() > 3));
// 按性别名字分组
Map<Byte, List<String>> gentleNameMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.groupingBy(User::getGentle, Collectors.mapping(User::getName, Collectors.toList())));
// 按性别年龄总和分组
Map<Byte, Integer> gentleTotalAgeMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.groupingBy(User::getGentle, Collectors.reducing(0, User::getAge, Integer::sum)));
// 迭代操作
Stream.iterate(0, i -> i + 1).limit(list.size()).forEach(i -> {
System.out.println(list.get(i).getName());
});
// guava table转换
Table<Long, String, Integer> idNameRankTable = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().map(user -> ImmutableTable.of(user.getId(), user.getName(), user.getRank())).collect(HashBasedTable::create, HashBasedTable::putAll, HashBasedTable::putAll);
// stream只能被terminal一次,下面是错误示范
Stream<User> stream = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream();
stream.collect(Collectors.toMap(User::getId, Function.identity()));
stream.collect(Collectors.toMap(User::getId, User::getName)); // java.lang.IllegalStateException: stream has already been operated upon or closed
// ssc-common的com.meicloud.mcu.common.util.StreamUtil简单封装了一些流操作,欢迎试用
// 参考资料:https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html
来源:https://blog.csdn.net/wangmuming/article/details/72747183
标签:Java8,Stream,过滤,null值
0
投稿
猜你喜欢
浅析Java常用API(Scanner,Random)匿名对象
2023-05-04 09:42:39
intellij idea中spring boot properties文件不能自动提示问题解决
2021-09-24 09:53:46
基于StreamRead和StreamWriter的使用(实例讲解)
2022-09-11 22:12:36
非常实用的侧滑删除控件SwipeLayout
2023-02-01 14:52:39
C# 操作符之二 算数操作符
2023-06-19 20:21:13
SpringSecurity实现访问控制url匹配
2021-11-03 00:18:16
java两个integer数据判断相等用==还是equals
2021-06-14 00:46:52
详解Android studio中正确引入so文件的方法
2022-06-17 23:21:32
安卓自定义流程进度图控件实例代码
2023-10-30 00:07:23
C#简单输出日历的方法
2023-11-13 05:56:10
Android使用Retrofit上传文件功能
2022-08-28 08:42:38
C#实现通过程序自动抓取远程Web网页信息的代码
2023-12-04 22:56:46
Android多媒体之VideoView视频播放器
2023-11-12 14:38:35
Java字节码中jvm实例用法
2023-08-08 05:25:09
Java实现的3des加密解密工具类示例
2023-08-21 14:00:01
C#将时间转成文件名使用方法
2022-08-15 05:59:22
解析Kotlin JSON格式
2021-07-16 08:09:35
图形学之Unity渲染管线流程分析
2023-09-25 05:27:36
android中ListView数据刷新时的同步方法
2022-02-01 16:34:45
SpringBoot如何动态修改Scheduled(系统启动默认执行,动态修改)
2023-11-29 06:13:27