Java 8 – 从一个 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());


References

  1. Objects::nonNull JavaDoc
  2. Java 8 Streams filter examples
  3. Java 8 Collectors JavaDoc

转:http://blog.csdn.net/wangmuming/article/details/72747183

posted @ 2018-02-23 14:21  舞羊  阅读(6432)  评论(0编辑  收藏  举报