Java 8– filters null values from a stream __java

Source: Internet
Author: User

Review an example of a stream containing null data. 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::p rintln);

    }

Output

Java
python
node
null   //<---null
ruby
null   //<---null
php
Solution (resolution)

To solve the above problem, we use: 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::p rintln);


    }

Output

Java
python
node
Ruby
php

In addition, the filter can also be used: Objects::nonnull

Import java.util.List;

	list<string> result = Language.filter (objects::nonnull). Collect (Collectors.tolist ());
ReferencesObjects::nonnull Javadoc Java 8 Streams Filter Examples Java 8 collectors JavaDoc

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.