新旧数据比较 直接可用

我自定义的函数式编程自定义接口 可替换为java.util.function.Function
java 复制代码
public interface RSupplier<T,V> {

    V apply(T t);
}
对比类
java 复制代码
package xxx.utils;

import xxx.RSupplier;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//T为实体类时需要重写hashCode和equals方法
public class NewOldComparer<T> {

	private List<T> insertObjs = new ArrayList<>();

	private List<T> updateObjs = new ArrayList<>();

	private List<T> deleteObjs = new ArrayList<>();

	public NewOldComparer(List<T> newObjs, List<T> oldObjs, RSupplier<T, Long> idSupplier) {
		if (null != newObjs && !newObjs.isEmpty()) {
			compareHisRecord(newObjs, oldObjs, idSupplier);
		} else {
			noHasNewIds(oldObjs);
		}
	}

	public List<T> insertObjs() {
		return insertObjs;
	}

	public List<T> updateObjs() {
		return updateObjs;
	}

	public List<T> deleteObjs() {
		return deleteObjs;
	}

	private void compareHisRecord(List<T> newObjects, List<T> oldObjects, RSupplier<T, Long> idSupplier) {
		if (oldObjects.isEmpty()) {
			this.insertObjs = newObjects;
		} else {
			Map<Long, T> oldObjMap = oldObjects.stream().collect(Collectors.toMap(idSupplier::apply, c -> c, (c1, c2) -> c1));
			Map<Long, T> newObjMap = newObjects.stream().collect(Collectors.toMap(idSupplier::apply, c -> c, (c1, c2) -> c1));
			for (T curObj : newObjects) {
				Long curId = idSupplier.apply(curObj);
				if (oldObjMap.get(curId) == null) {
					this.insertObjs.add(curObj);
				} else {
					T optObj = oldObjMap.get(idSupplier.apply(curObj));
					if (optObj != null && !optObj.equals(curObj)) {
						this.updateObjs.add(curObj);
					}
				}
			}
			for (T curOldObj : oldObjects) {
				if (newObjMap.get(idSupplier.apply(curOldObj)) == null) {
					this.deleteObjs.add(curOldObj);
				}
			}
		}
	}

	private void noHasNewIds(List<T> oldObjs) {
		if (null != oldObjs && !oldObjs.isEmpty()) {
			this.deleteObjs = oldObjs;
		}
	}
}
使用
java 复制代码
		//新数据
		List<Value> newValueList= new ArrayList<>();
		//旧数据
		List<Value> oldValueList= new ArrayList<>();
		//比较
		NewOldComparer<Value> comparer = new NewOldComparer<>(newValueList, oldValueList, Value::getRid);
        List<Value> insertList = comparer.insertObjs();
        List<Value> deleteList = comparer.deleteObjs();
        List<Value> updateList = comparer.updateObjs();
        //后续逻辑...

具体比较哪些字段,需要在对象重写的equals和hashCode自定义

相关推荐
!if7 分钟前
springboot mybatisplus 配置SQL日志,但是没有日志输出
spring boot·sql·mybatis
学Java的bb7 分钟前
MybatisPlus
java·开发语言·数据库
讓丄帝愛伱8 分钟前
Mybatis Log Free插件使用
java·开发语言·mybatis
重生之我要当java大帝10 分钟前
java微服务-尚医通-编写医院设置接口上
java·数据库·微服务
夫唯不争,故无尤也10 分钟前
Tomcat 内嵌启动时找不到 Web 应用的路径
java·前端·tomcat
心之伊始11 分钟前
Netty线程模型与Tomcat线程模型对比分析
java·开发语言
gaoshan1234567891013 分钟前
‌MyBatis-Plus 的 LambdaQueryWrapper 可以实现 OR 条件查询‌
java·tomcat·mybatis
Mu.38722 分钟前
初始Spring
java·数据库·spring
葡萄城技术团队24 分钟前
突破Excel局限!SpreadJS让电子表格“活”起来
java·数据库·excel
吹个口哨写代码32 分钟前
处理文本编辑器存的json格式报错问题,对编辑器存的字段进行转换处理,再通过json返回
java·编辑器·json