最近在写一个业务时,需要同步第三方的一个字典表,每次都是全量同步,由于查询压力比较大,我又不能每次全删了重新存。因此需要比较出新增、编辑、删除的项。于是随手写了个工具类。

public interface ListCompare {
    String getKey();
    boolean equals(Object o);
}

public class ListCompareUtil {

    public static <T extends ListCompare>CompareRes<T> compare(List<T> newList, List<T> oldList) {
        List<T> addList = new ArrayList<>();
        List<T> updateList = new ArrayList<>();
        List<T> delList = new ArrayList<>();

        Map<String, T> oldMap = oldList.stream().collect(Collectors.toMap(ListCompare::getKey, ListCompare -> ListCompare));
        Map<String, T> newMap = newList.stream().collect(Collectors.toMap(ListCompare::getKey, ListCompare -> ListCompare));
        for (T newObj : newList) {
            if (oldMap.containsKey(newObj.getKey())) {
                if (!oldMap.get(newObj.getKey()).equals(newObj)) {
                    updateList.add(newObj);
                }
            } else {
                addList.add(newObj);
            }
        }
        for (T oldObj : oldList) {
            if (!newMap.containsKey(oldObj.getKey())) {
                delList.add(oldObj);
            }
        }

        return new CompareRes<>(addList, updateList, delList);
    }
   }
@Data
public class CompareRes<T> {

    List<T> addList;

    List<T> updateList;

    List<T> delList;

    public CompareRes(List<T> addList, List<T> updateList, List<T> delList) {
        this.addList = addList;
        this.updateList = updateList;
        this.delList = delList;
    }
}

用的时候只需将类 实例化 ListCompare 接口,实现getKey和equals方法