Вот что я придумал G-C:
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.Multiset.Entry;
public class MultisetOp {
public static void main(String[] args) {
Multiset<Integer> ms1 = Multisets.newHashMultiset(1, 1, 2, 3, 4, 4, 4);
Multiset<Integer> ms2 = Multisets.newHashMultiset(1, 2, 3, 3,
4, 5, 5, 5);
Multiset<Integer> mu = Multisets.newHashMultiset();
Multiset<Integer> mi = Multisets.newHashMultiset();
// -------- UNION START -----------
for (Entry<Integer> e : ms1.entrySet()) {
int j = ms2.count(e.getElement());
mu.add(e.getElement(), Math.max(e.getCount(), j));
}
for (Entry<Integer> e : ms2.entrySet()) {
int j = ms1.count(e.getElement());
if (j == 0) {
mu.add(e.getElement(), e.getCount());
}
}
// -------- UNION END -----------
// -------- INTERSECT START -----------
for (Entry<Integer> e : ms1.entrySet()) {
int j = ms2.count(e.getElement());
if (j > 0) {
mi.add(e.getElement(), Math.min(e.getCount(), j));
}
}
// -------- INTERSECT END -----------
System.out.printf("Union: %s%n", mu);
System.out.printf("Intersection: %s%n", mi);
System.out.printf("Cardinality: %d%n", mu.size() - mi.size());
}
}
Результат:
[1 x 2, 2, 3 x 2, 4 x 3, 5 x 3]
[1, 2, 3, 4]
Не тестируется.
Кажется, ваша мощность может быть вычислена с двумя обходами вместо трех.