gpt4 book ai didi

java - 如何将ArrayList拆分为另一个List

转载 作者:行者123 更新时间:2023-12-02 05:26:00 35 4
gpt4 key购买 nike

我正在尝试将 ArrayList 拆分为单独的 block 。我有一个函数,它返回在 jsoupie 中收集的表数据,就像单个元素一样。我想知道如何制作第二个列表,以便它包含第一个列表的每 5 个后续元素。

   example:
1 list:
lista1.get (0) = Monday;
lista1.get (1) = Tuesday;
...
lista1.get (6) = Sunday;

and here I would like to make it

//lista1.get(1) .. lista1.get(6)
lista2.get (0) = Monday, Tuesday, Wednesday, Thursday, Friday;
lista2.get (1) = any, other data contained in, this, leaves, stated below;

谢谢

最佳答案

我给你写了两个方法。一种将列表拆分为列表列表,另一种将嵌套列表分组为单个字符串。

    public class LinkedListSplitByFive {

private static List<List<String>> splitByGroupAsList(List<String> list, int elementsInGroup) {
List<List<String>> result = new ArrayList<List<String>>();

List<String> group = new ArrayList<String>(elementsInGroup);
for (String s : list) {
group.add(s);
if (group.size() == elementsInGroup) {
result.add(group);
group = new ArrayList<String>(elementsInGroup);
}
}
if (!group.isEmpty()) {
result.add(group);
}
return result;
}

private static List<String> splitByGroupAsString(List<String> list, int elementsInGroup) {
List<List<String>> lists = splitByGroupAsList(list, elementsInGroup);
List<String> result = new ArrayList<String>(lists.size());

for (List<String> group : lists) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < group.size(); i++) {
sb.append(group.get(i));
if (i == group.size() - 1) {
sb.append(";");
} else {
sb.append(", ");
}
}
result.add(sb.toString());
}
return result;
}

public static void main(String[] args) {

List<String> list = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11");

System.out.println(splitByGroupAsList(list, 5));
// [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11]]

System.out.println(splitByGroupAsString(list, 5));
// [1, 2, 3, 4, 5;, 6, 7, 8, 9, 10;, 11;]
}
}

关于java - 如何将ArrayList拆分为另一个List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26000144/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com