I have a Java Set (specifically HashSet). Suppose it has a size of 10k. How can I break it into 5 Sets each of size 2k?
Guava has libraries to partition Iterable classes. The Iterables is a utility class which has static methods to partition Iterable classes. The return value is a Iterable of lists though. The given code shows how to do that.
Set<Integer> myIntSet = new HashSet<Integer>();
// fill the set
Iterable<List<Integer>> lists = Iterables.partition(myIntSet, SIZE_EACH_PARTITION);
This method will split the elements of the set so that the first set contains the first 2000, the second contains the next 2000, etc.
public static <T> List<Set<T>> split(Set<T> original, int count) {
// Create a list of sets to return.
ArrayList<Set<T>> result = new ArrayList<Set<T>>(count);
// Create an iterator for the original set.
Iterator<T> it = original.iterator();
// Calculate the required number of elements for each set.
int each = original.size() / count;
// Create each new set.
for (int i = 0; i < count; i++) {
HashSet<T> s = new HashSet<T>(original.size() / count + 1);
result.add(s);
for (int j = 0; j < each && it.hasNext(); j++) {
s.add(it.next());
}
}
return result;
}
//As example, in your code...
Set<Integer> originalSet = new HashSet<Integer>();
// [fill the set...]
List<Set<Integer>> splitSets = split(originalSet, 5);
Set<Integer> first = splitSets.get(0); // etc.
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