Skip to content

Commit

Permalink
fix: union
Browse files Browse the repository at this point in the history
  • Loading branch information
rouven-walter committed Jan 21, 2020
1 parent 72ebef6 commit 5d93520
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 7 additions & 1 deletion src/main/java/org/logicng/util/CollectionHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,15 @@ public static <T, C extends Collection<T>> C intersection(final Collection<T> co
* @return the union of the two collections as a set
*/
public static <T, C extends Collection<T>> C union(final Collection<T> col1, final Collection<T> col2, final Supplier<C> collectionFactory) {
if (col1 == null || col2 == null) {
if (col1 == null && col2 == null) {
return collectionFactory.get();
}
if (col1 == null) {
return col2.stream().distinct().collect(Collectors.toCollection(collectionFactory));
}
if (col2 == null) {
return col1.stream().distinct().collect(Collectors.toCollection(collectionFactory));
}
return Stream.concat(col1.stream(), col2.stream()).distinct().collect(Collectors.toCollection(collectionFactory));
}

Expand Down
4 changes: 2 additions & 2 deletions src/test/java/org/logicng/util/CollectionHelperTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public void testIntersection() {
public void testUnion() {
final List<String> strings1 = Arrays.asList("a", "b", "c", "a");
List<String> strings2 = Arrays.asList("c", "d", "e");
assertThat(CollectionHelper.<String, TreeSet<String>>union(strings1, null, TreeSet::new)).isEmpty();
assertThat(CollectionHelper.<String, TreeSet<String>>union(null, strings2, TreeSet::new)).isEmpty();
assertThat(CollectionHelper.<String, TreeSet<String>>union(strings1, null, TreeSet::new)).containsExactly("a", "b", "c");
assertThat(CollectionHelper.<String, TreeSet<String>>union(null, strings2, TreeSet::new)).containsExactly("c", "d", "e");
assertThat(CollectionHelper.<String, TreeSet<String>>union(strings1, strings2, TreeSet::new)).containsExactly("a", "b", "c", "d", "e");
strings2 = Arrays.asList("c", "d", "e", "a", "a", "a");
assertThat(CollectionHelper.<String, List<String>>union(strings1, strings2, ArrayList::new)).containsExactly("a", "b", "c", "d", "e");
Expand Down

0 comments on commit 5d93520

Please sign in to comment.