用于Java中的集合操作的API?

是否存在用于集合操作的API,例如Union,交集,差异,笛卡尔积,从集合到另一个集合的函数,域限制和这些函数的范围限制,….在Java中?

请评论(运营)和业绩的覆盖范围。

谢谢

是的,java Set类。

通过Java SE教程:

s1.containsAll(s2) – 如果s2是s1的子集,则返回true。 (如果set s1包含s2中的所有元素,则s2是s1的子集。)

s1.addAll(s2) – 将s1转换为s1和s2的并集。 (两个集合的并集是包含任一集合中包含的所有元素的集合。)

s1.retainAll(s2) – 将s1转换为s1和s2的交集。 (两个集合的交集是仅包含两个集合共有的元素的集合。)

s1.removeAll(s2) – 将s1转换为s1和s2的(非对称)集合差异。 (例如,s1减去s2的设定差值是包含在s1中找到但在s2中找不到的所有元素的集合。)

http://download.oracle.com/javase/tutorial/collections/interfaces/set.html

我不知道任何API,但已使用以下方法在Set上执行此类操作。

 public static  Set union(Set setA, Set setB) { Set tmp = new TreeSet(setA); tmp.addAll(setB); return tmp; } public static  Set intersection(Set setA, Set setB) { Set tmp = new TreeSet(); for (T x : setA) if (setB.contains(x)) tmp.add(x); return tmp; } public static  Set difference(Set setA, Set setB) { Set tmp = new TreeSet(setA); tmp.removeAll(setB); return tmp; } public static  Set symDifference(Set setA, Set setB) { Set tmpA; Set tmpB; tmpA = union(setA, setB); tmpB = intersection(setA, setB); return difference(tmpA, tmpB); } public static  boolean isSubset(Set setA, Set setB) { return setB.containsAll(setA); } public static  boolean isSuperset(Set setA, Set setB) { return setA.containsAll(setB); } 

参考: 设置操作:并集,交集,差异,对称差异,是子集,是超集

Google Guava库还有许多有用的方法(例如设置联合和差异)。

https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets

示例(来自上面链接的页面):

 Set wordsWithPrimeLength = ImmutableSet.of("one", "two", "three", "six", "seven", "eight"); Set primes = ImmutableSet.of("two", "three", "five", "seven"); SetView intersection = Sets.intersection(primes, wordsWithPrimeLength); // contains "two", "three", "seven" // I can use intersection as a Set directly, but copying it can be more efficient if I use it a lot. return intersection.immutableCopy(); 

java.util.Set类在其API中没有这些调用,但您可以将removeAll()retainAll()addAll()等操作组合在一起,以实现并集,交集和差异。 我不确定我知道你的域名限制是什么意思。

从API设置

您可以使用retainAll,removeAll和addAll方法“模拟”交集,差异,域限制,该方法接受任何Collection作为输入参数。