Java generalizes methods to validate nulls in object parameters

I'm trying to implement a logic. I have a POJO class with 7 properties

The following is the implementation

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

My question is not whether there is any general implementation I can try to write so many if loops

Solution

One of the best possible solutions is similar to the one I proposed earlier today

Use map < string, optional > Use the key of the future output mapping key to store the optional value of the checked attribute

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

Iterations using indexes allow you to perform map updates

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
}

Besides, I bet your intentions are a little different Map:: set has no method

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

Don't you want to put a list < < price >, on the contrary, an item to the same key?

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

Therefore, you can use the method I posted above

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>