Core Java

Adding a Non-Null Value to a Map in Java

When working with Java’s Map data structure, it is common to check whether a value is null before inserting it into the map. This helps prevent unnecessary null entries that might cause issues later. Let us delve into understanding Java Map and how to handle putting a value only if it is not null.

1. Introduction to Map in Java

In Java, a Map is a part of the java.util package and is used to store key-value pairs. Unlike lists or sets, which store individual elements, a Map stores values based on unique keys. This makes it an ideal choice when data needs to be accessed quickly using a key, rather than iterating through a list.

The Map interface does not extend the Collection interface but is a separate hierarchy. It provides methods to add, remove, and retrieve values based on keys. Some commonly used implementations of Map include:

  • HashMap: The most commonly used implementation. It allows null keys and values but does not guarantee any order.
  • TreeMap: Maintains a sorted order of keys based on natural ordering or a custom comparator.
  • LinkedHashMap: Maintains insertion order while offering fast lookups like HashMap.
  • Hashtable: A thread-safe implementation that does not allow null keys or values.

A Map does not allow duplicate keys, meaning each key maps to a single value. If a key is added again, its associated value is updated rather than creating a new entry.

2. Utilizing the if Statement

The simplest approach is to use an if statement to check whether the value is null before inserting it into the map. Consider the following example:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
import java.util.HashMap;
import java.util.Map;
 
public class IfStatementExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        String key = "username";
        String value = "john_doe";
 
        if (value != null) {
            map.put(key, value);
        }
 
        System.out.println(map); // Output: {username=john_doe}
    }
}

2.1 Code Explanation and Output

The given Java program demonstrates how to add a key-value pair to a HashMap only if the value is not null. It first creates a HashMap to store string keys and values. The key "username" and the value "john_doe" are defined as variables. Before inserting the value into the map, an if condition checks whether the value is not null to prevent inserting null values. Since value is non-null, it is added to the map using the put() method. Finally, the map is printed, displaying {username=john_doe} as output, confirming that the key-value pair has been successfully inserted.

1
{username=john_doe}

3. Utilizing the Optional.ifPresent() Method

Java 8 introduced the Optional class, which provides a more functional approach to handling null values. The Optional class was introduced in Java 8 as part of the java.util package is a container object that may or may not contain a non-null value. It helps in avoiding NullPointerException by providing a way to represent the presence or absence of a value explicitly. Instead of returning null, methods can return an Optional object, allowing developers to use functional programming techniques such as ifPresent(), orElse(), and map() to safely handle values. For example, Optional.ofNullable(value).ifPresent(System.out::println); prints the value only if it is non-null. This approach makes code more readable, reduces the need for explicit null checks, and encourages best practices for handling missing values.

Consider the following example:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
 
public class OptionalExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        String key = "email";
        String value = "john@example.com";
 
        Optional.ofNullable(value).ifPresent(val -> map.put(key, val));
 
        System.out.println(map); // Output: {email=john@example.com}
    }
}

3.1 Code Explanation and Output

This Java program demonstrates how to add a key-value pair to a HashMap using Optional to handle potential null values. It first creates a HashMap to store string keys and values. The key "email" and the value "john@example.com" are defined as variables. Instead of using an if statement, the program uses Optional.ofNullable(value).ifPresent(), which ensures that the value is added to the map only if it is non-null. If the value is present, the lambda function val -> map.put(key, val) executes, inserting the key-value pair into the map. Since the value is non-null, the final output is {email=john@example.com}, confirming that the key-value pair has been successfully added.

1
{email=john@example.com}

4. Utilizing the Stream.filter() Method

Another functional approach is to use Java Streams along with Stream.filter() to check for non-null values before inserting them into the map.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
 
public class StreamFilterExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        String key = "phone";
        String value = "123-456-7890";
 
        Stream.of(value)
              .filter(v -> v != null)
              .forEach(v -> map.put(key, v));
 
        System.out.println(map); // Output: {phone=123-456-7890}
    }
}

4.1 Code Explanation and Output

This Java program demonstrates how to add a key-value pair to a HashMap using Java Streams to handle potential null values. It initializes a HashMap and defines a key "phone" and a value "123-456-7890". The Stream.of(value) method creates a single-element stream containing the value, which is then filtered using .filter(v -> v != null) to exclude null values. If the value passes the filter (i.e., it is not null), .forEach(v -> map.put(key, v)) inserts it into the map. Since the value is non-null, the final output is {phone=123-456-7890}, confirming that the key-value pair has been successfully added.

1
{phone=123-456-7890}

5. Conclusion

In this article, we explored different ways to insert values into a Map only if they are not null, including the if statement, which provides a simple and readable approach, the Optional.ifPresent() method, which is useful in functional programming, and the Stream.filter() method, which offers an alternative functional approach. Each approach has its advantages, and the choice depends on the context and coding style preferences.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
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