java - 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 循环有没有我可以在这里尝试的通用实现。
解决方案
您可以使用
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())));
推荐阅读
- javascript - 以 HTML 格式打印变量的动态值,无需重新加载页面
- swift - 当应用程序在 iOS 11.4.1 中处于后台时,静默通知不起作用
- jquery - 附加数据后,单击事件不起作用jquery
- python - “for”循环和映射之间的区别
- java - 写入项目中已存在的 CSV 文件
- excel - 根据excel中的值列表选择整行
- angular - html 功能模块未加载角度 6
- java - Java中的字符编码
- angular-cli - 如何在 `angular.json` 中配置内联样式和 html 模板?
- javascript - MediaStreamRecorder 不是构造函数