Merge pull request #937 from GRain-long/patch-1

[新特性]添加intersectionDistinct方法
This commit is contained in:
Golden Looly 2020-06-28 11:26:03 +08:00 committed by GitHub
commit 37c2c07164
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 2 deletions

View File

@ -266,6 +266,39 @@ public class CollUtil {
}
return intersection;
}
/**
* 多个集合的交集<br>
* 针对一个集合中存在多个相同元素的情况只保留一个<br>
* 例如集合1[a, b, c, c, c]集合2[a, b, c, c]<br>
* 结果[a, b, c]此结果中只保留了一个c
*
* @param <T> 集合元素类型
* @param coll1 集合1
* @param coll2 集合2
* @param otherColls 其它集合
* @return 并集的集合返回 {@link LinkedHashSet}
*/
@SafeVarargs
public static <T> Set<T> intersectionDistinct(Collection<T> coll1, Collection<T> coll2, Collection<T>... otherColls) {
final Set<T> result;
if (isEmpty(coll1)) {
result = new LinkedHashSet<>();
} else {
result = new LinkedHashSet<>(coll1);
}
if (isNotEmpty(coll2)) {
result.retainAll(coll2);
}
if (ArrayUtil.isNotEmpty(otherColls)) {
for (Collection<T> otherColl : otherColls) {
result.retainAll(otherColl);
}
}
return result;
}
/**
* 两个集合的差集<br>

View File

@ -76,8 +76,21 @@ public class CollUtilTest {
ArrayList<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d");
Collection<String> union = CollUtil.intersection(list1, list2);
Assert.assertEquals(2, CollUtil.count(union, t -> t.equals("b")));
Collection<String> intersection = CollUtil.intersection(list1, list2);
Assert.assertEquals(2, CollUtil.count(intersection, t -> t.equals("b")));
}
@Test
public void intersectionTest2() {
ArrayList<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d");
ArrayList<String> list3 = CollUtil.newArrayList();
Collection<String> intersectionDistinct = CollUtil.intersectionDistinct(list1, list2);
Assert.assertEquals(CollUtil.newLinkedHashSet("a", "b", "c", "d"), intersectionDistinct);
Collection<String> intersectionDistinct2 = CollUtil.intersectionDistinct(list1, list2, list3);
Assert.assertTrue(intersectionDistinct2.isEmpty());
}
@Test