com.xzchaoo.commons.basic.diff.DiffUtils Maven / Gradle / Ivy
package com.xzchaoo.commons.basic.diff;
import com.xzchaoo.commons.basic.function.TriConsumer;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* Diff utilities
*
* @author xzchaoo
*
created at 2020/9/23
*/
public final class DiffUtils {
private DiffUtils() {
}
/**
* Diff two {@link Iterable}s.
*
* @param left left iterable
* @param right right iterable
* @param leftContain left contain predicate
* @param rightContain right contain predicate
* @param leftOnly left-only consumer
* @param rightOnly right-only consumer
* @param intersection intersection consumer
* @param element type
*/
public static void diff(Iterable left, //
Iterable right, //
Predicate leftContain, //
Predicate rightContain, //
Consumer leftOnly, //
Consumer rightOnly, //
Consumer intersection) {
for (T t : left) {
if (rightContain.test(t)) {
intersection.accept(t);
} else {
leftOnly.accept(t);
}
}
for (T t : right) {
if (!leftContain.test(t)) {
rightOnly.accept(t);
}
}
}
/**
* Diff two map
*
* @param left left map
* @param right right map
* @param leftOnly left-only consumer
* @param rightOnly right-only consumer
* @param intersection intersection consumer
* @param key type
* @param value type
*/
public static void diff2(Map left, //
Map right, //
BiConsumer leftOnly, //
BiConsumer rightOnly, //
TriConsumer intersection) {
for (Map.Entry e : left.entrySet()) {
K k = e.getKey();
V v = e.getValue();
if (right.containsKey(k)) {
intersection.accept(k, v, right.get(k));
} else {
leftOnly.accept(k, v);
}
}
for (Map.Entry e : right.entrySet()) {
if (!left.containsKey(e.getKey())) {
rightOnly.accept(e.getKey(), e.getValue());
}
}
}
}