首页 > 解决方案 > Java 泛化方法来验证对象参数中的空值

问题描述

我正在尝试实现一个逻辑,其中我有一个具有 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 循环有没有我可以在这里尝试的通用实现。

标签: javalistdictionaryfor-loopjava-8

解决方案


您可以使用

Map<String,List<PriceClass>> map = new HashMap<>();
for(PriceClass price: prices) {
    HashMap<String,Object> options = new HashMap<>();
    options.put("attibute1", price.getAttribute1());
    options.put("attibute2", price.getAttribute2());
    options.put("attibute3", price.getAttribute3());
    options.put("attibute4", price.getAttribute4());
    options.put("attibute5", price.getAttribute5());
    options.put("attibute6", price.getAttribute6());
    options.put("attibute7", price.getAttribute7());
    options.values().removeIf(Objects::isNull);
    options.keySet().forEach(attr -> map.computeIfAbsent(attr, x -> new ArrayList<>())
                                        .add(price));
}

或概括该过程:

准备一次不可修改的地图

static final Map<String, Function<PriceClass,Object>> ATTR;
static {
  Map<String, Function<PriceClass,Object>> a = new HashMap<>();
  a.put("attibute1", PriceClass::getAttribute1);
  a.put("attibute2", PriceClass::getAttribute2);
  a.put("attibute3", PriceClass::getAttribute3);
  a.put("attibute4", PriceClass::getAttribute4);
  a.put("attibute5", PriceClass::getAttribute5);
  a.put("attibute6", PriceClass::getAttribute6);
  a.put("attibute7", PriceClass::getAttribute7);
  ATTR = Collections.unmodifiableMap(a);
}

并使用

Map<String,List<PriceClass>> map = new HashMap<>();
for(PriceClass price: prices) {
    HashMap<String,Object> options = new HashMap<>();
    ATTR.forEach((attr,func) -> options.put(attr, func.apply(price)));
    options.values().removeIf(Objects::isNull);
    options.keySet().forEach(attr -> map.computeIfAbsent(attr, x -> new ArrayList<>())
                                        .add(price));
}

或者

Map<String,List<PriceClass>> map = prices.stream()
    .flatMap(price -> ATTR.entrySet().stream()
        .filter(e -> e.getValue().apply(price) != null)
        .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), price)))
    .collect(Collectors.groupingBy(Map.Entry::getKey,
                Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

推荐阅读