| Author |
Subdividing a Collection into smaller collections
|
Promod kumar
Ranch Hand
Joined: Jun 26, 2006
Posts: 90
|
|
Here is the requirement I have to split a collection into n collections each of a given size. Here is the code, I came up with. I am guessing there is a better way to do this or is there a Collection Utility that does it for me. I looked but could not find it (did a google search and Java ranch search). Any pointers would be great and thanks for your time.
|
 |
Promod kumar
Ranch Hand
Joined: Jun 26, 2006
Posts: 90
|
|
|
I actually found a sublist after I posted the message. Is that the better way of doing this.
|
 |
Ganesh Gowtham
Ranch Hand
Joined: Mar 30, 2005
Posts: 221
|
|
public class CollectionSplitter { static List split(List srcList, int index) { List d = new ArrayList(); for (int i = 0; i < srcList.size(); i = i + 4) { if ((i + 4) <= srcList.size()) d.add(srcList.subList(i, i + 4)); else d.add(srcList.subList(i, srcList.size() - 1)); } return d; } public static void main(String[] args) { List resultList = new ArrayList(); List list = new ArrayList(); list.add("one"); list.add("two"); list.add("three"); list.add("four"); list.add("five"); list.add("six"); list.add("seven"); list.add("eight"); list.add("nine"); list.add("ten"); list.add("eleven"); resultList = split(list, 5); } } if there is still simple let me know
|
Thanks, Ganesh Gowtham
http://ganesh.gowtham.googlepages.com
|
 |
Promod kumar
Ranch Hand
Joined: Jun 26, 2006
Posts: 90
|
|
Gowtham, Yours looks simple. Anyway here is my new version
|
 |
Vihung Marathe
Greenhorn
Joined: Apr 24, 2006
Posts: 7
|
|
How about something like
|
 |
Niran Abeygunawardena
Greenhorn
Joined: Oct 13, 2009
Posts: 3
|
|
I realise this an old post but it comes up high in web searches for this topic.
So, here is an alternative solution basically adapted from the google collections apis. It uses generics to return a list of lists which are of the specified size. Just call the static method partition() with your parameters.
|
 |
Lars Vogel
Ranch Hand
Joined: Oct 10, 2007
Posts: 55
|
|
Hello,
thanks this discussion was helpful. Based on your discussion I have created a little summary and a JUnit test which can be found here:
http://www.vogella.de/articles/JavaAlgorithmsPartitionCollection/article.html
I did include this discussion as the source of information in the article.
Thanks again, Lars
|
Tutorials about Java, Eclipse and Webprogramming http://www.vogella.de
|
 |
Mehmet Ali Kipcak
Greenhorn
Joined: Nov 04, 2011
Posts: 1
|
|
Niran Abeygunawardena wrote:I realise this an old post but it comes up high in web searches for this topic.
So, There is another alternative solution by using enumerations and not instantiating multiple list objects at once .
|
 |
 |
|
|
subject: Subdividing a Collection into smaller collections
|
|
|