加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java概括方法来验证对象参数中的null

发布时间:2020-12-15 08:27:03 所属栏目:Java 来源:网络整理
导读:我正在尝试实现一个逻辑,我有一个有7个属性的POJO类. 我已将这些POJO类添加到地图中取决于属性的值. 以下是实施 MapString,ListPriceClass map = new HashMap();for (PriceClass price : prices) { if (price.getAttribute1() !=null) { if (map.get("attrib
我正在尝试实现一个逻辑,我有一个有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
   }
}

我的问题不是写这么多if if循环是否有任何我可以尝试的通用实现.

解决方法

一个可能的最佳解决方案类似于我今天早些时候提出的 one.

使用Map< String,Optional<?>>使用将来输出映射键的键存储checked属性的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))

因此,您可以使用我在上面发布的方式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读