如果我的内部对象为空,Optional.ofNullable 似乎不起作用?



我有一个嵌套的类结构,用于反序列化我的数据:

Class A has a single property that is an object of Class B (say b)
Class B has a single property that is an object of Class C (say c)
Class C has a single property that is an object of Class D (say d)
Class D has a single property that is a a string (say e)

我有看起来像的数据

Map<String, List<Map<String, Map<String, Map<String, Map<String, String>>>>>> input =
ImmutableMap.of("Key",
ImmutableList.of(ImmutableMap.of("a",
ImmutableMap.of("b",
ImmutableMap.of("c",
ImmutableMap.of("d", "e"))))));

我想解析这个多级地图,并将结果放入地图中

Map<String, String> result = new HashMap<>();

最后,我希望result映射在末尾包含以下内容:["key", "e"]

如果地图包含所有中间密钥a, b, c and d,我有这个代码可以工作

mapping.entrySet()
.stream()
.map(l -> l.getValue().stream()
.map(Optional::ofNullable)
.map(opta -> opta.map(A::getB))
.map(optb -> optb.map(B::getC))
.map(optc -> optc.map(C::getD))
.map(optd -> optd.map(D::getE))
.map(optv -> optv.orElse("default"))
.map(m -> result.put(l.getKey(), m))
.count())
.count();

但例如,如果输入是

Map<String, List<Map<String, Map<String, Map<String, Map<String, String>>>>>> input =
ImmutableMap.of("Key",
ImmutableList.of(ImmutableMap.of("a",
ImmutableMap.of("b",null))));

然后我的代码失败了:

java.lang.NullPointerException: null value in entry: b=null

为什么我的Optional.isNullable不工作?

您使用的是ImmutableMap,而ImmutableMap不喜欢null键或值:https://guava.dev/releases/23.0/api/docs/com/google/common/collect/ImmutableMap.html#of-K-V-

public static <K,V> ImmutableMap<K,V> of(K k1, V v1)

返回包含单个条目的不可变映射。此贴图的行为并且与Collections.singletonMap(K, V)的性能相当,但将不接受空键或值。它主要适用于代码的一致性和可维护性。

消息是通过以下方法生成的:https://github.com/google/guava/blob/82b3e9806dc3422e51ecb9400d8f50404b083dde/guava/src/com/google/common/collect/CollectPreconditions.java#L28

static void checkEntryNotNull(Object key, Object value) {
if (key == null) {
throw new NullPointerException("null key in entry: null=" + value);
} else if (value == null) {
throw new NullPointerException("null value in entry: " + key + "=null");
}
}

另一方面,我认为你应该使用专业而不是地图。。。我敢肯定,这种类型会让你的团队或其他读者头疼:

Map<String, List<Map<String, Map<String, Map<String, Map<String, String>>>>>>

最新更新