Replace null values with default value in Java Map

JavaServer Side ProgrammingProgramming

To replace null values with default value in Java Map, the code is as follows −

Example

 Live Demo

import java.util.*;
import java.util.stream.*;
public class Demo{
   public static <T, K> Map<K, T> null_vals(Map<K, T> my_map, T def_val){
      my_map = my_map.entrySet().stream().map(entry -> {
         if (entry.getValue() == null)
         entry.setValue(def_val);
         return entry;
      })
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
      return my_map;
   }
   public static void main(String[] args){
      Map<Integer, Integer> my_map = new HashMap<>();
      my_map.put(1, null);
      my_map.put(2, 56);
      my_map.put(3, null);
      my_map.put(4, 99);
      int defaultValue = 0;
      System.out.println("The map with null values is : "+ my_map);
      my_map = null_vals(my_map, defaultValue);
      System.out.println("The map with null values replaced is : " + my_map);
   }
}

Output

The map with null values is : {1=null, 2=56, 3=null, 4=99}
The map with null values replaced is : {1=0, 2=56, 3=0, 4=99}

A class named Demo contains a function named ‘null_vals’ that checks for null values in an array and replaces them with a default value that is previously defined. In the main function, a Map instance is created and elements are pushed into it using the ‘put’ function. The ‘null_vals’ function is called on this map and the null values are replaced with a default value.

raja
Published on 08-Jul-2020 10:27:42
Advertisements