在前文(高級JAVA - 利用函數式接口實現通用的取並集/交集/差集)中我們實現了利用函數式接口獲取交集/差集 , 但是隻能全部生成 , 假如我們只需要一個交集的話 , 所有代碼仍然會執行一次 . 比較浪費資源 , 故再改進一版
package com.xing.dto;
import com.xing.common.utils.XDataUtil;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @title 兩個集合的聚合數據 , 包含並集/交集/差集
* @author Xingbz
* @createDate 2019-7-23
*/
public class GatherData<T, R> {
/** 新數據集合 */
private List<T> newList;
/** 舊數據集合(一般爲數據庫記錄) */
private List<T> oldList;
/** 新數據標識值集合 */
private List<R> newIdList;
/** 舊數據標識值集合 */
private List<R> oldIdList;
/** 業務轉換對象(處理兩個集合中用來標識唯一的屬性) */
private Function<T, R> func;
/** 並集 - 新集合加舊集合的數據(去重) */
private List<T> unionList;
/** 交集 - 新集合和舊集合都有的數據 */
private List<T> intersectList;
/** 主差集 - 新集合有 , 舊集合沒有的數據 */
private List<T> exceptMainList;
/** 次差價 - 舊集合有 , 新集合沒有的數據 */
private List<T> exceptMinorList;
/** 構造器私有 , 僅可通過對外的工廠方法訪問 */
private GatherData(List<T> newList, List<T> oldList, Function<T, R> func) {
this.newList = newList;
this.oldList = oldList;
this.func = func;
}
private List<R> getNewIdList() {
if (Objects.isNull(newIdList)) {
newIdList = newList.stream().map(func).collect(Collectors.toList());
}
return newIdList;
}
private List<R> getOldIdList() {
if (Objects.isNull(oldIdList)) {
oldIdList = oldList.stream().map(func).collect(Collectors.toList());
}
return oldIdList;
}
/** @title 獲取並集 */
public List<T> getUnionList() {
if (Objects.isNull(unionList)) {
unionList = XDataUtil.addAllList(getIntersectList(), getExceptMainList(), getExceptMinorList());
}
return unionList;
}
/** @title 獲取交集 */
public List<T> getIntersectList() {
if (Objects.isNull(intersectList)) {
intersectList = oldList.stream().filter(t -> getNewIdList().contains(func.apply(t))).collect(Collectors.toList());
}
return intersectList;
}
/** @title 獲取主差集 */
public List<T> getExceptMainList() {
if (Objects.isNull(exceptMainList)) {
exceptMainList = newList.stream().filter(t -> !getOldIdList().contains(func.apply(t))).collect(Collectors.toList());
}
return exceptMainList;
}
/** @title 獲取次差集 */
public List<T> getExceptMinorList() {
if (Objects.isNull(exceptMinorList)) {
exceptMinorList = oldList.stream().filter(t -> !getNewIdList().contains(func.apply(t))).collect(Collectors.toList());
}
return exceptMinorList;
}
/** 遍歷交集操作 */
public void unionEach(Consumer<? super T> consumer) {
getUnionList().forEach(consumer);
}
/** 遍歷交集操作 */
public void intersectEach(Consumer<? super T> consumer) {
getIntersectList().forEach(consumer);
}
/** 遍歷主差集操作 */
public void exceptMainEach(Consumer<? super T> consumer) {
getExceptMainList().forEach(consumer);
}
/** 遍歷次差集操作 */
public void exceptMinorEach(Consumer<? super T> consumer) {
getExceptMinorList().forEach(consumer);
}
/** 對外方法 , 實例化數據 */
public static <T, R> GatherData<T, R> instance(List<T> newList, List<T> oldList, Function<T, R> func) {
return new GatherData<>(newList, oldList, func);
}
}