3 回答

TA贡献1810条经验 获得超4个赞
您可以使用它subList(int fromIndex, int toIndex)来查看原始列表的一部分。
来自API:
返回此列表中指定的fromIndex,包含的和toIndex独占的部分的视图。(如果fromIndex且toIndex相等,则返回的列表为空。)返回的列表由此列表支持,因此返回列表中的非结构更改将反映在此列表中,反之亦然。返回的列表支持此列表支持的所有可选列表操作。
例:
List<Integer> numbers = new ArrayList<Integer>(
Arrays.asList(5,3,1,2,9,5,0,7)
);
List<Integer> head = numbers.subList(0, 4);
List<Integer> tail = numbers.subList(4, 8);
System.out.println(head); // prints "[5, 3, 1, 2]"
System.out.println(tail); // prints "[9, 5, 0, 7]"
Collections.sort(head);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7]"
tail.add(-1);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7, -1]"
如果您需要这些切碎的列表不是视图,那么只需List从中创建一个新的subList。以下是将这些内容放在一起的示例:
// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
List<List<T>> parts = new ArrayList<List<T>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<T>(
list.subList(i, Math.min(N, i + L)))
);
}
return parts;
}
List<Integer> numbers = Collections.unmodifiableList(
Arrays.asList(5,3,1,2,9,5,0,7)
);
List<List<Integer>> parts = chopped(numbers, 3);
System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
parts.get(0).add(-1);
System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]"
System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)

TA贡献1803条经验 获得超3个赞
您可以将Guava库添加到项目中,并使用Lists.partition方法,例如
List<Integer> bigList = ...List<List<Integer>> smallerLists = Lists.partition(bigList, 10);

TA贡献1876条经验 获得超5个赞
Apache Commons Collections 4在类中有一个分区方法ListUtils
。以下是它的工作原理:
import org.apache.commons.collections4.ListUtils;...int targetSize = 100;List<Integer> largeList = ...List<List<Integer>> output = ListUtils.partition(largeList, targetSize);
添加回答
举报