オブジェクトパラメータにNULLを検証するアプローチを一般化するJava

SREE:

私は7つの属性を持つPOJOクラスを持っているロジックを実装しようとしています。私は、属性の値に依存マップにこれらのPOJOクラスを追加しました。

下記の実装です

Map<String,List<PriceClass>> map = new HashMap();
for (PriceClass price : prices) {
  if (price.getAttribute1() !=null) {
      if (map.get("attribute1") !=null) {
             map.get("attribute1").add(price);
      } else {
           map.set("attibute1",Collections.singletonList(price))
      }
   } else if(price.getAttribute2()!=null) {
       if (map.get("attribute12") !=null) {
             map.get("attribute2").add(price);
       } else {
           map.set("attibute2",Collections.singletonList(price))
       }
   } else if (price.getAttribute3() !=null) {
     .
     .
     .
   } else if (price.getAttribute7() !=null) {
       //update the map
   }
}

ループは、私がここに試すことができます任意の一般化の実装がある場合、私の質問は、これらの多くを書くのではなく、です。

ニコラス:

おそらく、最適なソリューションは次のようになり1今日は早く示唆しています。

使用Map<String, Optional<?>>保存するためにOptional、将来の出力マップキーのキーで確認した属性の値を。

Map<String, Optional<?>> options = new HashMap<>();
options.put("attribute1", Optional.ofNullable(price.getAttribute1()));
// ...
options.put("attribute3", Optional.ofNullable(price.getAttribute2()));
// ...

インデックスの反復を使用すると、マップの更新を実行できます。

Map<String,List<Price>> map = new HashMap();
for (int i=1; i<7; i++) {                                      // attributes 1..7
    String attribute = "attribute" + i;                        // attribute1...attribute7
    options.get(attribute).ifPresent(any ->                    // for non-nulls
               map.put(                                        // put to the map
                   attribute,                                  // attribute as key remains
                   Optional.ofNullable(map.get(attribute))     // gets the existing list
                           .orElse(new ArrayList<>())          // or creates empty
                           .add(price)));                      // adds the current Price
}

また、私はあなたの意図が少し違っていた賭けます。方法はありませんMap::set

map.set("attibute1",Collections.singletonList(price))

あなたは置くことを意味するものではありませんでしたList<Price>代わりに、非常に同じキーに一つのアイテムで?

map.put("attibute1", Collections.singletonList(price))

このような理由から、私は上記の投稿の方法を使用することができます。

おすすめ

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