If you ensure that y (and x) are/become sorted, like the class TreeSet
, the following uses a special merging (internal method addAllForTreeSet
).
for (Set<Integer> x : listA) {
for (SortedSet<Integer> y : listB) {
SortedSet<Integer> u = new TreeSet(x);
u.addAll(y);
SortedSet<Integer> i = new TreeSet(x);
i.retainAll(y);
}
}
Whether this is actually faster I am not sure.
Better would be if the integers are not too wild, limited to say 10_000. If the values are non-negative, one can immediately use a BitSet
instead of a Set<Integer>
.
This is unbeatable. Use a BitSet constructor with a probable capacity (like 10_000).
for (BitSet x : listA) {
for (BitSet y : listB) {
BitSet u = x.clone();
u.or(y);
BitSet i = x.clone();
i.and(y);
}
}
Ýou might use a parallel stream to save a factor equal to the number of processors.
listA.parallelStream().forEach(x -> {});
That is a secundary optimisation.
Guava I did not use in the last years, did it not have sets of primitive type int
?