Java 如何将 ArrayList 拆分为多个列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1910236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I split an ArrayList into several lists?
提问by Arthur Ronald
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 chartas follows:
我需要显示一个谷歌图表如下:
To generate its values, I just call
要生成其值,我只需调用
StringUtils.join(values, ","); // outputs 0,1,2,3,4,5,6
It happens it supports up to1000 pixel width. So if I have many values, I need to split my ArrayList into other ArrayLists to generate other charts. Something like:
它恰好支持高达1000 像素的宽度。所以如果我有很多值,我需要将我的 ArrayList 拆分为其他 ArrayList 以生成其他图表。就像是:
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?
我应该使用什么助手来实现我的目标?
采纳答案by Kevin Bourrillion
google-collections has Lists.partition(). You supply the size for each sublist.
google-collections 有Lists.partition()。您提供每个子列表的大小。
回答by BalusC
To start, you may find List#subList()
useful. Here's a basic example:
首先,您可能会发现List#subList()
很有用。这是一个基本示例:
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
.
回答by johnnieb
Apache Commons Collections 4has a partitionmethod in the ListUtils
class. Here's how it works:
Apache Commons Collections 4 类中有一个分区方法ListUtils
。这是它的工作原理:
import org.apache.commons.collections4.ListUtils;
...
int targetSize = 3;
List<Integer> values = ...
List<List<Integer>> output = ListUtils.partition(values, targetSize);