JAVA8-Predicate functions use
The main explanation
Predicate accepts an input parameter and returns a boolean result. The interface comprises a plurality of default methods to be combined into other complex Predicate logic (such as: and, or, not). Interface parameters may be used to verify the request, determine whether there are changes to the new and old data update operation. add- and, or- or, negate- non
Title common method
1. Analyzing boolean test (T t);
Real scene
General check request parameters, determines whether to change the data
public class CommonUtils {
//参数校验
public static <T> void checkParams(T t, Map<String, Predicate<T>> map) {
if (isNotEmpty(map)) {
map.entrySet().forEach(r -> {
if (r.getValue().test(t))
throw new PandaException(PandaCodes.BAD_PARAM, r.getKey());
});
}
}
//数据变更校验
public static <T> boolean checkDataIsChange(T t, List<Predicate<T>> list) {
if (isNotEmpty(list)) {
return list.stream().anyMatch(r -> r.test(t));
}
return false;
}
}
Such as: parameter calibrating
private Map<String,Predicate<SkuPlatPriceVo>> getCheckParamRules() {
Map<String, Predicate<SkuPlatPriceVo>> map = new HashMap<>();
map.put("平台现价需要为0-无穷大", r -> r.getPlatePrice() < 0);
map.put("平台的platform不能为空", r -> ParamChecker.isBlank(r.getPlatform()));
return map
}
//校验页面传入的skuPlatPriceVo参数:CommonUtils.checkParams(skuPlatPriceVo,getCheckParamRules());
Such as: data change check
private List<Predicate<SkuPlatPriceVo>> getCheckDataIsChangeRules(PcCustomPriceDTO oldData) {
List<Predicate<SkuPlatPriceVo>> list = new ArrayList<>();
list.add(r -> oldData.getPrice() != null && r.getPlatePrice() != oldData.getPrice());
list.add(r -> oldData.getRebate() != null && r.getRebate() != oldData.getRebate());
return list;
}
//校验页面传入的更新操作skuPlatPriceVo数据是否需要发生变更要执行数据库update操作
if(CommonUtils.checkDataIsChange(skuPlatPriceVo,getCheckDataIsChangeRules(dto))){
//数据库数据更新
}