0

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
  • Where did you get stuck? Commented May 24, 2010 at 9:01

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 get a java compiler version 5 or later.
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 .
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.
ok now i know - the rounding of the length/peaces division was causing the problem in your initial code :) thanks again
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.