Java 8 Stream Filter 过滤null值

Java 8 Stream Filter 过滤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

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());
    原文作者:最后的miku殿下
    原文地址: https://blog.csdn.net/Hatsune_Miku_/article/details/73432351
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞