开发者

How can I split an ArrayList into several lists?

开发者 https://www.devze.com 2022-12-13 22:41 出处:网络
See the following ArrayList: List<Integer> values = new ArrayList<Integer>(); values.add(0);

See the following ArrayList:

List<Integer> values = new ArrayList<Integer>();
values.add(0);
values.add(1);
values.add(2);
values.add(3);
values.add(4);
values.add(5);
values.add(6);

So we have:

integerList.size(); // outputs 7 elements

I need to show a Google chart as follows:

http://chart.apis.google.com/chart?chs=300x200&chd=t:60,-1,80,60,70,35&cht=bvg&chbh=20,4,20&chco=4C5F2B,BED730,323C19&chxt=y&chxr=0,0,500

To generate its values, I just call

StringUtils.join(values, ","); // outputs 0,1,2,3,4,5,6

It happens it supports up to 1000 pixel width. So if I have many values, I need to split my ArrayList into other ArrayLists to generate other charts. Something like:

Integer targetSize = 3;开发者_运维技巧 // And suppose each target ArrayList has size equal to 3

// ANSWER GOES HERE
List<List<Integer>> output = SomeHelper.split(values, targetSize);

What Helper should I use to get my goal?


google-collections has Lists.partition(). You supply the size for each sublist.


To start, you may find List#subList() useful. Here's a basic example:

public static void main(String... args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(0);
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4);
    list.add(5);
    list.add(6);

    int targetSize = 3;
    List<List<Integer>> lists = split(list, targetSize);
    System.out.println(lists); // [[0, 1, 2], [3, 4, 5], [6]]
}

public static <T extends Object> List<List<T>> split(List<T> list, int targetSize) {
    List<List<T>> lists = new ArrayList<List<T>>();
    for (int i = 0; i < list.size(); i += targetSize) {
        lists.add(list.subList(i, Math.min(i + targetSize, list.size())));
    }
    return lists;
}

Note that I didn't use the splittedInto as it doesn't make much sense in combination with targetSize.


Apache Commons Collections 4 has a partition method in the ListUtils class. Here’s how it works:

import org.apache.commons.collections4.ListUtils;
...

int targetSize = 3;
List<Integer> values = ...
List<List<Integer>> output = ListUtils.partition(values, targetSize);
0

精彩评论

暂无评论...
验证码 换一张
取 消