[英]How can I split an ArrayList into several lists?
See the following ArrayList: 请参阅以下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: 我需要按如下方式显示Google图表 :
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 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. 它发生它支持高达 1000像素的宽度。 So if I have many values, I need to split my ArrayList into other ArrayLists to generate other charts. 因此,如果我有很多值,我需要将ArrayList拆分为其他ArrayLists以生成其他图表。 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() . google-collections有Lists.partition() 。 You supply the size for each sublist. 您提供每个子列表的大小。
To start, you may find List#subList()
useful. 首先,您可能会发现List#subList()
很有用。 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
. 请注意,我没有使用splittedInto
,因为它不具有太大的意义结合targetSize
。
Apache Commons Collections 4 has a partition method in the ListUtils
class. Apache Commons Collections 4在ListUtils
类中有一个分区方法。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.