当前位置: 首页 > 图灵资讯 > 技术篇> Java 8 – 从一个 Stream中过滤null值

Java 8 – 从一个 Stream中过滤null值

来源:图灵教育
时间:2023-06-25 14:18:46

复习Streama 包含 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, "图灵"); List<String> result = language.collect(Collectors.toList()); result.forEach(System.out::println); }}outputjavapythonnodenull   // <--- NULLrubynull   // <--- NULL图灵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, "图灵"); //List<String> result = language.collect(Collectors.toList()); List<String> result = language.filter(x -> x!=null).collect(Collectors.toList()); result.forEach(System.out::println);  }}此外,outputjavapythonoderuby图灵,过滤器也可以使用: Objects::nonNull import java.util.List; List<String> result = language.filter(Objects::nonNull).collect(Collectors.toList());