如何从一个列表中填充三个arrayLists,即从index1到lista1的值,从index2到lista2的值,从index3到lista3的值,从index4到lista1的值等等?
ArrayList<String> lista = new ArrayList<String>();
ArrayList<String> lista1 = new ArrayList<String>();
ArrayList<String> lista2 = new ArrayList<String>();
ArrayList<String> lista3 = new ArrayList<String>();
sh.forEach(row -> {
row.forEach(cell -> {
String cellvalue = dataFormatter.formatCellValue(cell);
lista.add(cellvalue);
});
});
答案 0 :(得分:3)
ArrayList<String> lista = new ArrayList<String>();
ArrayList<String> lista1 = new ArrayList<String>();
ArrayList<String> lista2 = new ArrayList<String>();
ArrayList<String> lista3 = new ArrayList<String>();
ArrayList<String>[] newLists = new ArrayList[]{lista1, lista2, lista3};
for (int i=0 ; i< lista.size(); i ++ ){
newLists[i % 3].add(lista.get(i));
}
答案 1 :(得分:3)
您可以在三个元素的数组中添加三个列表,并使用传统的for循环对其进行迭代。这是修改后的代码
ArrayList<String> lista = new ArrayList<String>();
ArrayList<String>[] lists = new ArrayList[3];
lists[0] = new ArrayList<String>();
lists[1] = new ArrayList<String>();
lists[2] = new ArrayList<String>();
for(int i = 0; i < lista.size(); i++){
lists[i % lists.length].add(lista.get(i));
}
答案 2 :(得分:1)
Java8 +流API,您可以尝试
List<String> lista = Arrays.asList("A","B","C","D","E");
List<String> list1 = lista.stream()
.filter(x -> lista.indexOf(x) % 3 == 0)
.collect(Collectors.toList());
List<String> list2 = lista.stream()
.filter(x -> lista.indexOf(x) % 3 == 1)
.collect(Collectors.toList());
List<String> list3 = lista.stream()
.filter(x -> lista.indexOf(x) % 3 == 2)
.collect(Collectors.toList());