猿问

Java:如何在多个小型ArrayLists中拆分ArrayList?

Java:如何在多个小型ArrayLists中拆分ArrayList?

如何在相同大小(= 10)的多个ArrayLists中拆分ArrayList(size = 1000)?

ArrayList<Integer> results;


哆啦的时光机
浏览 1240回答 3
3回答

蝴蝶不菲

您可以使用它subList(int fromIndex, int toIndex)来查看原始列表的一部分。来自API:返回此列表中指定的fromIndex,包含的和toIndex独占的部分的视图。(如果fromIndex且toIndex相等,则返回的列表为空。)返回的列表由此列表支持,因此返回列表中的非结构更改将反映在此列表中,反之亦然。返回的列表支持此列表支持的所有可选列表操作。例:List<Integer> numbers = new ArrayList<Integer>(&nbsp; &nbsp; 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 Lstatic <T> List<List<T>> chopped(List<T> list, final int L) {&nbsp; &nbsp; List<List<T>> parts = new ArrayList<List<T>>();&nbsp; &nbsp; final int N = list.size();&nbsp; &nbsp; for (int i = 0; i < N; i += L) {&nbsp; &nbsp; &nbsp; &nbsp; parts.add(new ArrayList<T>(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.subList(i, Math.min(N, i + L)))&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }&nbsp; &nbsp; return parts;}List<Integer> numbers = Collections.unmodifiableList(&nbsp; &nbsp; 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!)

繁星点点滴滴

您可以将Guava库添加到项目中,并使用Lists.partition方法,例如List<Integer>&nbsp;bigList&nbsp;=&nbsp;...List<List<Integer>>&nbsp;smallerLists&nbsp;=&nbsp;Lists.partition(bigList,&nbsp;10);

慕运维8079593

Apache Commons Collections 4在类中有一个分区方法ListUtils。以下是它的工作原理:import&nbsp;org.apache.commons.collections4.ListUtils;...int&nbsp;targetSize&nbsp;=&nbsp;100;List<Integer>&nbsp;largeList&nbsp;=&nbsp;...List<List<Integer>>&nbsp;output&nbsp;=&nbsp;ListUtils.partition(largeList,&nbsp;targetSize);
随时随地看视频慕课网APP

相关分类

Java
我要回答