在Java中,将List拆分为两个子列表可以通过以下几种方法实现:
subList()
方法:List<String> originalList = Arrays.asList("A", "B", "C", "D", "E");
int midpoint = originalList.size() / 2;
List<String> firstSubList = originalList.subList(0, midpoint);
List<String> secondSubList = originalList.subList(midpoint, originalList.size());
Lists.partition()
方法(需要导入Guava库):List<String> originalList = Arrays.asList("A", "B", "C", "D", "E");
List<List<String>> twoSubLists = Lists.partition(originalList, originalList.size() / 2);
List<String> firstSubList = twoSubLists.get(0);
List<String> secondSubList = twoSubLists.get(1);
List<String> originalList = Arrays.asList("A", "B", "C", "D", "E");
int midpoint = originalList.size() / 2;
List<String> firstSubList = new ArrayList<>();
List<String> secondSubList = new ArrayList<>();
for (int i = 0; i< originalList.size(); i++) {
if (i < midpoint) {
firstSubList.add(originalList.get(i));
} else {
secondSubList.add(originalList.get(i));
}
}
这三种方法都可以将原始列表拆分为两个子列表。请注意,这些方法不会修改原始列表。如果需要修改原始列表,请使用其他数据结构,例如数组。
领取专属 10元无门槛券
手把手带您无忧上云