背景:业务上会有一些增删改主从关系的情景,前端会把主从关系的信息一起传到后台,再由后台同时维护主从关系信息,这里示例一个对维护主从关系增删改的方法
工具方法
public static List<String> subList1HaveList2NotHave(List<String> list1, List<String> list2) {
Map<String, String> tempMap = list2.parallelStream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldData, newData) -> newData));
return list1.parallelStream().filter(str -> {
return !tempMap.containsKey(str);
}).collect(Collectors.toList());
}
public static List<String> intersection(List<String> list1, List<String> list2) {
return list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
}
方法体
if (CollUtil.isNotEmpty(itemVo)) {
List<String> listIds = list.stream().map(op -> op.getId()).collect(Collectors.toList());
List<String> itemIds = itemVo.stream().filter(op -> StrUtil.isNotEmpty(op.getId())).map(op -> op.getId()).collect(Collectors.toList());
List<String> strings = subList1HaveList2NotHave(listIds, itemIds);
if (CollUtil.isNotEmpty(strings)) {
xxxxxService.removeBatchByIds(strings);
}
List<String> intersection = intersection(listIds, itemIds);
if (CollUtil.isNotEmpty(intersection)) {
List<xxxx> collect = itemVo.stream().filter(op -> intersection.contains(op.getId())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(collect)) {
xxxxxService.updateBatchById(collect);
}
}
List<xxxx> collect = itemVo.stream().filter(op -> StrUtil.isEmpty(op.getId())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(collect)) {
xxxxxService.saveBatch(collect);
}
}