tags:

views:

66

answers:

2

Can someone please give the Java equivalent of the below python (which slices a given array into given parts) which was originally written by ChristopheD here:

def split_list(alist, wanted_parts=1):
   length = len(alist)
   return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] 
            for i in range(wanted_parts) ]

I don't know any python but can really use the above code in my Java app. Thanks

+1  A: 

Maybe something like this:

List<List<T>> splitList(List<T> alist, int wantedParts) {
    ArrayList<List<T>> result = new ArrayList<List<T>>();
    int length = alist.length;

    for (int i = 0; i < wantedParts; i++) {
        result.append(alist.subList(i*length/wantedParts,
                                    (i+1)*length/wantedParts));
    }

    return result;
}

If your alist will be structurally modified later in any way, you will have to make a copy of the sublist created by the subList method within the code, otherwise the results will be unpredictable.

Tamás
Thanks for your code Tamas.One problem though.sublist returns a List<Integer> but when i try to declare a List<Integer> it tells me "The type List is not generic; it cannot be parameterized with arguments <Integer>". it won't accept ArrayList<Integer> for result? What can i do there?
techventure
@techventure get a java compiler version 5 or later.
Pete Kirkham
ok managed to get it working.There's a problem with the code when the Lists isn't of even number size.for example a list of 9 numbers, it only goes upto 8 .
techventure
Re-written it a bit, this one should work better.
Tamás
Works great Tamas, but i can't see what changed to make it work, to me it seems like you only changed "single_list_length" to length/wantedPeaces which is the same thing? Thank you for taking the time. much appreciated.
techventure
ok now i know - the rounding of the length/peaces division was causing the problem in your initial code :) thanks again
techventure
A: 

Don't reinvent the wheel, the google collections api has a function called partition which does precisely that