Core Java

Converting a Null Array to an Empty List in Java

In Java, handling null arrays is a common scenario, especially when working with APIs or legacy code that may return null instead of an empty array. This can cause issues if not properly handled, especially when converting such arrays to lists. An efficient and reliable conversion ensures that null values are replaced with empty lists, avoiding potential NullPointerException. This article demonstrates multiple approaches for converting a null array to an empty list, focusing on standard Java features as well as a popular third-party library.

1. Initial Setup for Demonstration

Before diving into the solutions, let’s set up a simple scenario to demonstrate the problem. Suppose we have a method that might return a null array, and we want to safely convert it to a list, ensuring it is never null.

Here’s an example to set the stage:

public class NullArrayToListDemo {
    public static void main(String[] args) {
        String[] nullArray = null;

        // Simulating a null array scenario
        System.out.println("Original array: " + nullArray);
    }
}

In this code snippet, nullArray is initialized as null. The goal is to convert this null array into an empty List.

2. Stream-Based Approach

Java 8’s Stream API simplifies handling null values and effectively converts a null array to an empty list. By combining the power of Optional with streams, we can ensure a concise and safe conversion as shown below.

public class NullArrayToListUsingStreams {
    private static final Logger logger = Logger.getLogger(NullArrayToListUsingStreams.class.getName());

    public static void main(String[] args) {
        String[] nullArray = null;

        List<String> resultList = Optional.ofNullable(nullArray)
                .map(Arrays::stream)
                .orElseGet(Stream::empty)
                .collect(Collectors.toList());

        logger.log(Level.INFO, "Resulting list: {0}", resultList);
    }
}

This example starts by wrapping the potentially null array (nullArray) in an Optional using Optional.ofNullable. If the array is not null, it is converted to a stream using Arrays.stream. If the array is null, the orElseGet method provides an empty stream as a fallback. The stream is then collected into a list using Collectors.toList.

3. Using Ternary Operator

When working with older versions of Java or if you prefer a more explicit approach, the ternary operator can be a simple and efficient way to handle the null check and conversion.

Here’s how it can be implemented:

public class NullArrayToListUsingTernary {
    
    private static final Logger logger = Logger.getLogger(NullArrayToListUsingTernary.class.getName());
    public static void main(String[] args) {
        String[] nullArray = null;

        List<String> resultList = (nullArray != null) ? Arrays.asList(nullArray) : List.of();

        logger.log(Level.INFO, "Resulting list: {0}", resultList);
    }
}

This approach directly checks if the array is null. If it is not null, it converts it to a list using Arrays.asList(). If it is null, it returns an immutable empty list using List.of(). Note that List.of() is available starting in Java 9.

Output:

Java null array to empty list conversion using a ternary operator example output

4. Using Apache Commons Lang

Apache Commons Lang is a popular third-party library that offers utility methods for handling null values and simplifying common programming tasks. The ArrayUtils class provides a nullToEmpty method, which is perfect for this use case.

First, we need to add the maven dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.17.0</version>
</dependency>

Here is an example of using Apache Commons Lang:

public class NullArrayToListUsingApacheCommons {
    private static final Logger logger = Logger.getLogger(NullArrayToListUsingApacheCommons.class.getName());
    
    public static void main(String[] args) {
        String[] nullArray = null;

        String[] safeArray = ArrayUtils.nullToEmpty(nullArray);
        List<String> resultList = Arrays.asList(safeArray);

        logger.log(Level.INFO, "Resulting list: {0}", resultList);
    }
}

In this implementation:

  • ArrayUtils.nullToEmpty(nullArray) converts the null array to an empty array.
  • Arrays.asList(safeArray) converts the safe array into a list.

This method is especially useful if your project already uses Apache Commons Lang, as it reduces boilerplate code.

5. Conclusion

In this article, we explored different approaches to convert a null array into an empty list in Java. Using Java 8 Streams, we demonstrated a modern, functional way to handle null values efficiently, leveraging Optional and the Stream API for safe and concise code. Whether we are working with legacy code or building new applications, these techniques provide reliable solutions to handle null arrays effectively.

6. Download the Source Code

This article covered how to convert a null array to an empty list in Java.

Download
You can download the full source code of this example here: convert a null array to empty list in Java

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button