本文介绍: 我自定义的函数式编程自定义接口 可替换为java.util.function.Functionpublic interface RSupplier<T,V> { V apply(T t);}对比类package xxx.utils;import xxx.RSupplier;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.stream.Co
我自定义的函数式编程自定义接口 可替换为java.util.function.Function
public interface RSupplier<T,V> {

    V apply(T t);
}
对比类
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;
		}
	}
}
使用
		//新数据
		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自定义

原文地址:https://blog.csdn.net/HolyLordHanChaun/article/details/135527512

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_54729.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注