私の内側のオブジェクトがnullの場合Optional.ofNullableが動作するようには思えないのですか?

SAGAR KALBURGI:

私は私のデータをデシリアライズするために使用するネストされたクラス構造を持っています:

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-KV-

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=341694&siteId=1