com.github.sseserver.util.DifferentComparatorUtil Maven / Gradle / Ivy
package com.github.sseserver.util;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 比较两个对象的不同之处
*
* @author hao
*/
public class DifferentComparatorUtil {
public static ListDiffResult listDiff(Collection before, Collection after) {
return listDiff(before, after, e -> e);
}
public static ListDiffResult listDiff(Collection extends E> before, Collection extends E> after, Function idFunction) {
if (before == null) {
before = Collections.emptyList();
}
if (after == null) {
after = Collections.emptyList();
}
Map leftMap = before.stream()
.collect(Collectors.toMap(idFunction, e -> e, (o1, o2) -> o1, LinkedHashMap::new));
Map rightMap = after.stream()
.collect(Collectors.toMap(idFunction, e -> e, (o1, o2) -> o1, LinkedHashMap::new));
ListDiffResult result = new ListDiffResult<>();
for (Map.Entry entry : leftMap.entrySet()) {
if (rightMap.containsKey(entry.getKey())) {
} else {
result.getDeleteList().add(entry.getValue());
}
}
for (Map.Entry entry : rightMap.entrySet()) {
if (leftMap.containsKey(entry.getKey())) {
} else {
result.getInsertList().add(entry.getValue());
}
}
return result;
}
public static class ListDiffResult {
private final List insertList = new ArrayList<>();
private final List deleteList = new ArrayList<>();
public List getInsertList() {
return insertList;
}
public List getDeleteList() {
return deleteList;
}
public boolean isEmpty() {
return insertList.isEmpty() && deleteList.isEmpty();
}
}
}