Java 8 check if list is null or empty using Optional

Java 8 introduced the Optionalclass to make handling of nulls less error-prone. For example, the following program to pick the lucky name has a null check as:

public static final List NAMES = Arrays.asList["Rita", "Gita", "Nita", "Ritesh", "Nitesh", "Ganesh", "Yogen", "Prateema"]; public String pickLuckyNameOldWay[final List names, final String startingLetter] { String luckyName = null; for [String name : names] { if [name.startsWith[startingLetter]] { luckyName = name; break; } } return luckyName != null ? luckyName : "No lucky name found"; }

This null check can be replaced with the Optional  class method isPresent[]  as shown below:

public String pickLuckyNameWIsPresent[final List names, final String startingLetter] { final Optional luckyName = names.stream[].filter[name -> name.startsWith[startingLetter]].findFirst[]; return luckyName.isPresent[] ? luckyName.get[] : "No lucky name found"; }

However, notice the writing is no easier than:

return luckyName != null ? luckyName : "No lucky name found";

The Optional  class, however, supports other techniques that are superior to checking nulls. The above code can be re-written as below with  orElse[]  method as below:

public String pickLuckyNameWOrElse[final List names, final String startingLetter] { final Optional luckyName = names.stream[].filter[name -> name.startsWith[startingLetter]].findFirst[]; return luckyName.orElse["No lucky name found"]; }

The method orElse[]  is invoked with the condition "If X is null, populate X. Return X.", so that the default value can be set if the optional value is not present.

There is another method called the ifPresent[Function]. You can use this method to invoke an action and skip the null case completely. For example, the program below prints a message in the case, if the condition is met as:

public static void pickLuckyNameOldWay[final List names, final String startingLetter] { String luckyName = null; for [String name : names] { if [name.startsWith[startingLetter]] { luckyName = name; break; } } if [luckyName != null] { postMessage[luckyName]; } } public static void postMessage[final String winnerName] { System.out.println[String.format["Congratulations, %s!", winnerName]]; }

This can be re-written with ifPresent[] , as shown below. in a more intuitive manner, as:

public static void pickLuckyNameNewWay[final List names, final String startingLetter] { final Optional luckyName = names.stream[].filter[name -> name.startsWith[startingLetter]].findFirst[]; luckyName.ifPresent[OptionalIfPresent::postMessage]; }

If we want to throw an exception in case if no name is found, then it would be something like this:

public String pickLuckyNameOldWay[final List names, final String startingLetter] { String luckyName = null; // ... same code here if [luckyName == null] { throw new NotFoundException["There is no name starting with letter."]; } return luckyName; }

It can be meaningfully replaced with orElseThrow as:

public String pickLuckyNameWOrElse[final List names, final String startingLetter] { final Optional luckyName = names.stream[].filter[name -> name.startsWith[startingLetter]].findFirst[]; return luckyName.orElseThrow[[] -> new NotFoundException["There is no name starting with letter."]]; }

There are other many more methods in the Optional  class to handle null  in more proper way. You can go through the Optional in Java 8 cheat sheet.

As always, if you want to look into the source code for the example presented above, they are available on GitHub.

This post will discuss how to remove null values from a list using streams in Java.

We have discussed how to remove null values from a list in Java using plain Java, Guava library, and Apache Commons Collections in the previous post. This post will discuss how to remove nulls from the list using streams in Java 8 and above.

Java 8 introduced several enhancements to Collection interface, like removeIf[] method. It removes all elements of the list that satisfy the given predicate.

To remove null values from a list, we can pass Objects.nonNull[] to removeIf[] method:

import java.util.ArrayList;

import java.util.Objects;

    public static void main[String[] args]

        List colors = new ArrayList[Arrays.asList["RED", null, "BLUE", null, "GREEN"]];

        // using removeIf[] + Objects.isNull[]

        colors.removeIf[Objects::isNull];

        System.out.println[colors];

Download  Run Code

Output:
[RED, BLUE, GREEN]

 
There are many other ways to remove null values from a list using the removeIf[] method, as shown below:

colors.removeIf[x -> !Objects.nonNull[x]];

colors.removeIf[x -> x == null];

2. Using Java 8

We can use the Stream.filter[] method that returns a stream consisting of the elements that match the given predicate. We can specify a lambda expression or method reference to remove null values from the stream, as shown below:

import java.util.Objects;

import java.util.stream.Collectors;

    public static void main[String[] args]

        List colors = Arrays.asList["RED", null, "BLUE", null, "GREEN"];

                    .filter[x -> x != null]        // or `Objects::nonNull`

                    .collect[Collectors.toList[]];

        System.out.println[colors];

Download  Run Code

Output:
[RED, BLUE, GREEN]

 
This is equivalent to:

import java.util.List;import java.util.ArrayList;

    public static void main[String[] args]

        List colors = Arrays.asList["RED", null, "BLUE", null, "GREEN"];

        List list = new ArrayList[];

        for [String color : colors] {

        System.out.println[colors];

Download  Run Code

Output:
[RED, BLUE, GREEN]

3. Handle null list

Calling stream[] and removeIf[] methods on a null list will throw a NullPointerException. We can avoid that by creating an empty list [if list is null] using Optional.ofNullable[], as shown below:

import java.util.stream.Collectors;

    public static void main[String[] args]

        List colors = null;

        colors = Optional.ofNullable[colors]

                        .orElseGet[Collections::emptyList]

                        .collect[Collectors.toList[]];

        System.out.println[colors];

Download  Run Code

Output:
[]

4. Map the null values to a default value

Instead of removing null values from a list, we can replace the null values with any custom value. To illustrate, the following example replaces null values with a string.

import java.util.stream.Collectors;

    // using streams in Java 8 and above

    public static void main[String[] args]

        List colors = Arrays.asList["RED", null, "BLUE", null, "GREEN"];

                        .map[x -> [x == null] ? "####" : x]

                        .collect[Collectors.toList[]];

        System.out.println[colors];

Download  Run Code

Output:
[RED, ####, BLUE, ####, GREEN]

 
This is equivalent to:

import java.util.ArrayList;

    public static void main[String[] args]

        List colors = Arrays.asList["RED", null, "BLUE", null, "GREEN"];

        List list = new ArrayList[];

        for [String x : colors] {

            String s = [x == null] ? "####" : x;

        System.out.println[colors];

Download  Run Code

Output:
[RED, ####, BLUE, ####, GREEN]

That’s all about removing null values from a List in Java.


Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂


Video liên quan

Chủ Đề