Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I take a Java Set of size X and break into X/Y Sets?

Tags:

java

set

hashset

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?

like image 222
James Avatar asked May 08 '13 20:05

James


2 Answers

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);
like image 115
user2327870 Avatar answered Oct 21 '22 05:10

user2327870


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.
like image 37
wchargin Avatar answered Oct 21 '22 03:10

wchargin