Java8如何从一个Stream中过滤null值
目录
- 从一个Stream中过滤null值
- Solution(解决)
- stream 方法过滤条件的使用
- 下面以List为例
从一个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
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)