Java8如何从一个Stream中过滤null值

网友投稿 1809 2022-07-31


目录从一个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 language = Stream.of("java", "python", "node", null, "ruby", null, "php");

List result = language.collect(Collectors.toList());

result.forEach(System.out::println);

}

}

output

javapythonnodenull   // <--- NULLrubynull   // <--- NULLphp

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 language = Stream.of("java", "python", "node", null, "ruby", null, "php");

//List result = language.collect(Collectors.toList());

List result = language.filter(x -> x!=null).collect(Collectors.toList());

result.forEach(System.out::println);

}

}

output

javapythonnoderubyphp

另外,过滤器还可以用: Objects::nonNull

import java.util.List;

List 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

Stream 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 userList = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().filter(user -> (byte) 0 == user.getGentle()).collect(Collectors.toList());

// 获取排名大于1的用户年龄set

Set 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 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 idUserMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.toMap(User::getId, Function.identity()));

// 按唯一id,名字分组

Map idNameMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.toMap(User::getId, User::getName));

// 按年龄,名字分组,相同年龄的后出现的被覆盖

Map ageNameMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.toMap(User::getAge, User::getName, (a, b) -> a));

// 按性别分组

Map> gentleUserMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.groupingBy(User::getGentle));

// 按排名是否大于3分组

Map> partitionUserMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.partitioningBy(user -> user.getRank() > 3));

// 按性别名字分组

Map> gentleNameMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.groupingBy(User::getGentle, Collectors.mapping(User::getName, Collectors.toList())));

// 按性别年龄总和分组

Map 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 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 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://ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html

Stream 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 userList = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().filter(user -> (byte) 0 == user.getGentle()).collect(Collectors.toList());

// 获取排名大于1的用户年龄set

Set 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 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 idUserMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.toMap(User::getId, Function.identity()));

// 按唯一id,名字分组

Map idNameMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.toMap(User::getId, User::getName));

// 按年龄,名字分组,相同年龄的后出现的被覆盖

Map ageNameMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.toMap(User::getAge, User::getName, (a, b) -> a));

// 按性别分组

Map> gentleUserMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.groupingBy(User::getGentle));

// 按排名是否大于3分组

Map> partitionUserMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.partitioningBy(user -> user.getRank() > 3));

// 按性别名字分组

Map> gentleNameMap = Optional.ofNullable(list).orElseGet(Collections::emptyList).stream().collect(Collectors.groupingBy(User::getGentle, Collectors.mapping(User::getName, Collectors.toList())));

// 按性别年龄总和分组

Map 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 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 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://ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java8 stream中Collectors.toMap空指针问题及解决
下一篇:Spring Boot集成JavaMailSender发送邮件功能的实现
相关文章

 发表评论

暂时没有评论,来抢沙发吧~