最近研究hutool.core.collection.CollUtil类正好最近项目在用分享一下代码把
主要实现
//创建一个对象
@Data
@AllArgsConstructor
public class User {
private String code;
private String name;
private int age;
}
的就是A集合里的数据和B集合里的数据进行一个数据更新直接看代码把
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.log4j.Log4j2;
import java.util.*;
import java.util.stream.Collectors;
@Log4j2
public class Text {
/**
* 1.返回需要更新的数据
* 2.返回需要删除的数据
* 3.返回需要新增的数据
*
* @param args
*/
public static void main(String[] args) {
//旧数据
List<User> oldList = new java.util.ArrayList<>(List.of(
new User("001", "张飞", 18),
new User("002", "李四", 18),
new User("003", "王五", 18),
new User("004", "刘备", 18),
new User("005", "郭七", 18)
));
// List<User> oldList = new java.util.ArrayList<>();//测试空的集合
// List<User> newList = new java.util.ArrayList<>();
//需要更新的新数据
List<User> newList = List.of(
new User("001", "张费", 18),
new User("002", "李四", 19),
new User("003", "王五", 20),
new User("004", "刘备", 18),
new User("007", "老八", 18)
);
Set<String> newCodes = newList.stream().map(User::getCode).collect(Collectors.toSet());
Set<String> oldCodes = oldList.stream().map(User::getCode).collect(Collectors.toSet());
//删除的数据
oldList.stream().filter(x -> CollUtil.subtract(oldCodes, newCodes).contains(x.getCode())).collect(Collectors.toList()).forEach(x-> oldList.removeIf(c -> c.equals(x)));
//添加的数据
oldList.addAll(newList.stream().filter(x -> CollUtil.subtract(newCodes, oldCodes).contains(x.getCode())).collect(Collectors.toList()));
//更新的数据
List<User> update = newList.stream().filter(x -> CollUtil.intersectionDistinct(newCodes, oldCodes).contains(x.getCode())).collect(Collectors.toList());
update.forEach(x->{
User collect = oldList.stream().filter(c -> c.getCode().equals(x.getCode())).collect(Collectors.toList()).get(0);
if (!ObjectUtil.equals(collect,x)) {
//覆盖数据
oldList.set(oldList.indexOf(collect), x);
log.warn("更新的数据有:{}",x);
}
});
//Code排序
oldList.sort(Comparator.comparing(User::getCode));
oldList.forEach(System.out::println);
}
}
最终旧的oldList里的数据就是比对后数据
1.删除旧集合中没有新集合中有的数据
2.添加旧集合中没有新集合中有的数据
3.更新对比新旧集合都有的数据,name和age没有变动就跳过,如果有就直接set覆盖
更新的数据有:User(code=001, name=张费, age=18)
更新的数据有:User(code=002, name=李四, age=19)
更新的数据有:User(code=003, name=王五, age=20)
User(code=001, name=张费, age=18)
User(code=002, name=李四, age=19)
User(code=003, name=王五, age=20)
User(code=004, name=刘备, age=18)
User(code=007, name=老八, age=18)