I wrote something that does set splitting.
It uses intermediate arrays and lists.
It uses the methods Arrays.asList and Arrays.copyOfRange.
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class SetSplitTest { //define and initialize set private static Set<Integer> largeSet; static { largeSet = new HashSet<Integer>(); for (int i = 0; i < 10000; i++) { largeSet.add(i); } } public static void main() { System.out.println(largeSet); int amountOfSets = 5; //amount of subsets wanted Set<Integer>[] subsets = new Set[amountOfSets]; //array holding the subsets Integer[] largesetarray = largeSet.toArray(new Integer[largeSet.size()]); for (int i = 1; i <= amountOfSets; i++) { int fromIndex = (i-1) * largeSet.size() / amountOfSets; int toIndex = i * largeSet.size() / amountOfSets - 1; Set<Integer> subHashSet = new HashSet<Integer>(); subHashSet.addAll(Arrays.asList(Arrays.copyOfRange(largesetarray, fromIndex, toIndex))); subsets[i - 1] = subHashSet; } for (Set<Integer> subset : subsets) { System.out.println(subset); } } }
This, of course, is not the most elegant solution, but it is the best that I could come up with at that moment when you did not want to loop sets yourself.
source share