Java Map 用默认值替换空值
给定一个有空值的Map,任务是用一个默认值替换所有的空值。
例子。
输入 :map = {1=1, 2=2, 3=null, 4=4, 5=null, 6=null}, defaultValue = 0
输出 :{1=1, 2=2, 3=0, 4=4, 5=0, 6=0}。
输入 : map = {1=A, 2=B, 3=null, 4=D, 5=null, 6=null}, defaultValue = ‘Z’
输出 : {1=A, 2=B, 3=Z, 4=D, 5=Z, 6=Z}。
建议:请先在{IDE}上尝试你的方法,然后再继续解决
步骤:
- 获取带有空值的地图和要替换成的默认值。
- 使用Map.entrySet()方法获取地图的集合视图。
- 使用stream()方法将获得的集合视图转换为流。
- 现在用map()方法将空值映射为默认值。
- 使用collect()方法将修改后的流收集到Map中。
- 空值已经被成功地替换成了默认值。
下面是上述方法的实现。
例1:用整数。
// Java program to replace null values
// of a map with a default value
import java.util.*;
import java.util.stream.*;
class GFG {
// Function to replace the null values
public static <T, K> Map<K, T>
replaceNullValues(Map<K, T> map, T defaultValue)
{
// Replace the null value
map = map.entrySet()
.stream()
.map(entry -> {
if (entry.getValue() == null)
entry.setValue(defaultValue);
return entry;
})
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue));
return map;
}
public static void main(String[] args)
{
// Get the map
Map<Integer, Integer> map = new HashMap<>();
map.put(1, 1);
map.put(2, 2);
map.put(3, null);
map.put(4, 4);
map.put(5, null);
map.put(6, null);
// Get the default value
int defaultValue = 0;
// Print the original map
System.out.println("Map with null values: "
+ map);
// Replace the null values with the defaultValue
map = replaceNullValues(map, defaultValue);
// Print the modified map
System.out.println("Map with null value replaced: "
+ map);
}
}
输出。
Map with null values: {1=1, 2=2, 3=null, 4=4, 5=null, 6=null}
Map with null value replaced: {1=1, 2=2, 3=0, 4=4, 5=0, 6=0}
例子2:有字符。
// Java program to replace null values
// of a map with a default value
import java.util.*;
import java.util.stream.*;
class GFG {
// Function to replace the null values
public static <T, K> Map<K, T>
replaceNullValues(Map<K, T> map, T defaultValue)
{
// Replace the null value
map = map.entrySet()
.stream()
.map(entry -> {
if (entry.getValue() == null)
entry.setValue(defaultValue);
return entry;
})
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue));
return map;
}
public static void main(String[] args)
{
// Get the map
Map<Integer, Character> map = new HashMap<>();
map.put(1, 'A');
map.put(2, 'B');
map.put(3, null);
map.put(4, 'D');
map.put(5, null);
map.put(6, null);
// Get the default value
char defaultValue = 'Z';
// Print the original map
System.out.println("Map with null values: "
+ map);
// Replace the null values with the defaultValue
map = replaceNullValues(map, defaultValue);
// Print the modified map
System.out.println("Map with null value replaced: "
+ map);
}
}
输出。
Map with null values: {1=A, 2=B, 3=null, 4=D, 5=null, 6=null}
Map with null value replaced: {1=A, 2=B, 3=Z, 4=D, 5=Z, 6=Z}