Reputation: 183
I have a set, which I would like to divide into smaller sets of size x. Guava has something similar for lists - Lists.partition. But I couldn't find anything related to Sets. Are there any libraries which can help me in doing this? If not, what's the best way to break a set into smaller sets?
Edit: Currently, I'm doing it as follows:
int x = 10;
Set<String> stringSet = createHashSet();
for (List<String> partition : Iterables.partition(stringSet, x) {
doSomething(new HashSet<>(partition));
}
I'm using this Iterables.partition. There should be better ways to do it, which doesn't involve converting set to a list, and then back to a set.
Upvotes: 2
Views: 7900
Reputation: 159135
Set<Integer> input = /*defined elsewhere*/;
int x = 10;
List<Set<Integer>> output = new ArrayList<>();
Set<Integer> currSet = null;
for (Integer value : input) {
if (currSet == null || currSet.size() == x)
output.add(currSet = new HashSet<>());
currSet.add(value);
}
Result is, for all intends and purposes, random. It is undefined which elements of the input set going into which set of the output, and within an output set, the values will be in arbitrary order.
Upvotes: 1