Optional.ofNullable在我的内部对象为null时似乎不起作用?

问题描述 投票:1回答:1

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

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不起作用?

我具有用于反序列化数据的嵌套类结构:类A具有作为类B(例如b)的对象的单个属性。类B具有作为类C(例如c)的对象的单个属性。 ...

java stream
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.