新旧数据比较 直接可用

我自定义的函数式编程自定义接口 可替换为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自定义

相关推荐
勤奋的知更鸟16 分钟前
Java 编程之模板方法模式
java·开发语言·模板方法模式
逸风尊者37 分钟前
开发易掌握的知识:GeoHash查找附近空闲车辆
java·后端
碎叶城李白1 小时前
若依学习笔记1-validated
java·笔记·学习·validated
都叫我大帅哥2 小时前
🌊 Redis Stream深度探险:从秒杀系统到面试通关
java·redis
都叫我大帅哥2 小时前
Redis持久化全解析:从健忘症患者到记忆大师的逆袭
java·redis
程序猿阿越2 小时前
Kafka源码(一)Controller选举与创建Topic
java·后端·源码
程序无bug2 小时前
Spring6 当中 Bean 的生命周期的详细解析:有五步,有七步,有十步
java
二川bro2 小时前
飞算智造JavaAI:智能编程革命——AI重构Java开发新范式
java·人工智能·重构
Q_970956392 小时前
java+vue+SpringBoo校园失物招领网站(程序+数据库+报告+部署教程+答辩指导)
java·数据库·vue.js