在java中使用子列表划分数据
我有一个列表实现了ArrayList,它有大量的索引。我想要一份工作 将其放入单独的ArrayList中。我已尽我所能在java中使用子列表划分数据,java,arraylist,sublist,data-partitioning,Java,Arraylist,Sublist,Data Partitioning,我有一个列表实现了ArrayList,它有大量的索引。我想要一份工作 将其放入单独的ArrayList中。我已尽我所能 List<List<Integer>> list = new ArrayList<List<Integer>>(10000000); List<List<Integer>> sublist1 = list.subList(0,x) List<List<Inte
List<List<Integer>> list = new ArrayList<List<Integer>>(10000000);
List<List<Integer>> sublist1 = list.subList(0,x)
List<List<Integer>> sublist2 = list.subList(x,y)
这个列表很长。我想从上面的列表中获得一些小的子列表。每个列表都包含非重叠的内部列表:
sublist1:[[1,2,3][4,5,6] ...[.,.,.]] sublist2:[[,,,][] .... [,,,,]] sublistn:[[,,,][,,,]....[54,23,53]]
[编辑]
请不要混淆
[]
是空列表。我想显示列表中的列表数。我想您在这里稍微混淆了类型
也许这就是你想要的:
public static List<List<Integer>> getSubLists(List<Integer> ints, int k) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
for (int i = 0; i < ints.size(); i += k)
result.add(ints.subList(i, Math.min(i+k, ints.size())));
return result;
}
publicstaticlist获取子列表(List int,int k){
列表结果=新建ArrayList();
对于(int i=0;i
用法示例:
List<Integer> ints = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
List<List<Integer>> sublists = getSubLists(ints, 3);
// Prints [[10, 20, 30], [40, 50, 60], [70, 80, 90], [100]]
System.out.println(sublists);
List ints=Arrays.asList(10,20,30,40,50,60,70,80,90,100);
列表子列表=获取子列表(整数,3);
//打印[[10,20,30],[40,50,60],[70,80,90],[100]]
System.out.println(子列表);
下面是一个建议,遵循您的示例:
private static List<List<Integer>> getSubLists(List<List<Integer>> ints, int i) {
List<List<Integer>> sublist =
new ArrayList<List<Integer>>(Collections.nCopies(ints.size(),
Collections.<Integer>emptyList()));
sublist.set(i, ints.get(i));
return sublist;
}
我建议您详细了解java collection API来回答这个问题,因为它主要取决于访问类型和您在集合中访问的数据类型 没有任何进一步的细节,至少有两个好的建议:
为什么要有一个列表来存储一些索引?实际上,列表中包含了完整的信息。这就是为什么我把它放在列表中的原因。你们的分区方式是正确的。在你的例子中,你提供了更多关于你为什么这样做的细节,因此我看不出这个问题有什么意义。在你的例子中,
子列表2
不应该是[[][4,5,6]…[]]
?所以请将列表展平,使用我给出的第一个答案?谢谢你的回答。但是,这并不是我想要的。我将通过编辑问题来让你们明白
private static List<List<Integer>> getSubLists(List<List<Integer>> ints, int i) {
List<List<Integer>> sublist =
new ArrayList<List<Integer>>(Collections.nCopies(ints.size(),
Collections.<Integer>emptyList()));
sublist.set(i, ints.get(i));
return sublist;
}
List<List<Integer>> ints = Arrays.asList(Arrays.asList(1,2,3),
Arrays.asList(4,5,6),
Arrays.asList(54,23,53));
List<List<Integer>> subList0 = getSubLists(ints, 0);
List<List<Integer>> subList1 = getSubLists(ints, 1);
List<List<Integer>> subList2 = getSubLists(ints, 2);
System.out.println("subList0: " + subList0);
System.out.println("subList1: " + subList1);
System.out.println("subList2: " + subList2);
subList0: [[1, 2, 3], [], []]
subList1: [[], [4, 5, 6], []]
subList2: [[], [], [54, 23, 53]]