Is there an API for Set operations like Union, intersection, difference, Cartesian product, Function from a set to another, domain restriction and range restriction of those functions, .... in Java?
Please comment on coverage (of operations) and performance.
Thanks
Yes, the java Set
class.
Via Java SE tutorial:
s1.containsAll(s2)
— returns true if s2 is a subset of s1. (s2 is a subset of s1 if set s1 contains all of the elements in s2.)
s1.addAll(s2)
— transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all of the elements contained in either set.)
s1.retainAll(s2)
— transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.)
s1.removeAll(s2)
— transforms s1 into the (asymmetric) set difference of s1 and s2. (For example, the set difference of s1 minus s2 is the set containing all of the elements found in s1 but not in s2.)
http://download.oracle.com/javase/tutorial/collections/interfaces/set.html
I don't know any API but have used following methods do such things on Set.
public static <T> Set<T> union(Set<T> setA, Set<T> setB) {
Set<T> tmp = new TreeSet<T>(setA);
tmp.addAll(setB);
return tmp;
}
public static <T> Set<T> intersection(Set<T> setA, Set<T> setB) {
Set<T> tmp = new TreeSet<T>();
for (T x : setA)
if (setB.contains(x))
tmp.add(x);
return tmp;
}
public static <T> Set<T> difference(Set<T> setA, Set<T> setB) {
Set<T> tmp = new TreeSet<T>(setA);
tmp.removeAll(setB);
return tmp;
}
public static <T> Set<T> symDifference(Set<T> setA, Set<T> setB) {
Set<T> tmpA;
Set<T> tmpB;
tmpA = union(setA, setB);
tmpB = intersection(setA, setB);
return difference(tmpA, tmpB);
}
public static <T> boolean isSubset(Set<T> setA, Set<T> setB) {
return setB.containsAll(setA);
}
public static <T> boolean isSuperset(Set<T> setA, Set<T> setB) {
return setA.containsAll(setB);
}
Reference: Set operations: union, intersection, difference, symmetric difference, is subset, is superset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With