gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:00:05 26 4
gpt4 key购买 nike

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

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"]

如果 map 包含所有中间键a、b、c和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)

Returns an immutable map containing a single entry. This map behaves and performs comparably to Collections.singletonMap(K, V) but will not accept a null key or value. It is preferable mainly for consistency and maintainability of your code.

该消息是通过此方法生成的: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 ...我很确定这种类型会让您的团队或其他读者感到头疼:

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

关于java - 如果我的内部对象为空,Optional.ofNullable 似乎不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60780691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com