Last active
September 19, 2019 16:02
-
-
Save stevenwaterman/408666e0c1d27816fe2c73a533b745c2 to your computer and use it in GitHub Desktop.
How to get list of all duplicates in two collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Duplicates { | |
private static <T> BiFunction<Processing<T>, T, Processing<T>> getReducer(){ | |
return (acc, elem) -> { | |
if (acc.uniques.contains(elem)) { | |
acc.dupes.add(elem); | |
} else { | |
acc.uniques.add(elem); | |
} | |
return acc; | |
}; | |
} | |
private static <T> BinaryOperator<Processing<T>> getCombiner(){ | |
return (o1, o2) -> { | |
final Set<T> newDupes = new HashSet<>(o1.uniques); | |
newDupes.retainAll(o2.uniques); | |
newDupes.addAll(o2.dupes); | |
o1.dupes.addAll(newDupes); | |
return o1; | |
}; | |
} | |
public static <T> Set<T> getDuplicates(final Collection<T> elements){ | |
return elements.stream().reduce( | |
new Processing<>(), | |
getReducer(), | |
getCombiner() | |
).dupes; | |
} | |
private static class Processing<T>{ | |
public final Set<T> uniques = new HashSet<>(); | |
public final Set<T> dupes = new HashSet<>(); | |
} | |
} | |
/* ------------------------------------------ */ | |
public class AnyDuplicate { | |
private static <T> BiFunction<Processing<T>, T, Processing<T>> getReducer() { | |
return (acc, elem) -> { | |
if (acc.dupe == null) { | |
if (acc.uniques.contains(elem)) { | |
acc.dupe = elem; | |
} else { | |
acc.uniques.add(elem); | |
} | |
} | |
return acc; | |
}; | |
} | |
private static <T> BinaryOperator<Processing<T>> getCombiner() { | |
return (o1, o2) -> { | |
T dupe = o1.dupe; | |
if (dupe == null) { | |
dupe = o2.dupe; | |
} | |
if (dupe == null) { | |
dupe = o2.uniques.stream() | |
.filter(o1.uniques::contains) | |
.findAny() | |
.orElse(null); | |
} | |
if(dupe == null){ | |
o1.uniques.addAll(o2.uniques); | |
} else { | |
o1.dupe = dupe; | |
} | |
return o1; | |
}; | |
} | |
public static <T> T getAnyDuplicate(final Collection<T> elements) { | |
return elements.stream().reduce( | |
new Processing<>(), | |
getReducer(), | |
getCombiner() | |
).dupe; | |
} | |
private static class Processing<T> { | |
public final Set<T> uniques = new HashSet<>(); | |
public T dupe; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment