我有一个大小为1000的数组。我想像这样使用流操作来执行: -
List list= new ArrayList();
//list is initialize to 1000 elements
List subList = list.subList(0, 100);
// perform some operaions over the subarray
List subList1 = list.subList(101, 200);
// perform some operaions over the subarray
.... so on
}
我想要使用流API的代码。提前致谢
关于什么 :
List<List<Integer>> result = IntStream.range(0, list.size() / 100)
.mapToObj(index -> list.subList(index * 100, index * 100 + 100))
.collect(Collectors.toList());
你可以使用Collectors.partitioningBy
:
Map<Boolean, List<Integer>> map = list.stream().collect(Collectors.partitioningBy(element -> list.indexOf(element) >= 100));
and then do:
List<List<Integer>> results = new ArrayList(map.values());
更新:Collectors.partitioningBy
采用谓词,因此无法解决所需的用例。
或者如果你想将列表拆分成相等的部分(我认为更多是你的用例),你可以使用Collectors.groupingBy()
:
Map<Integer, List<Integer>> groups =
list.stream().collect(Collectors.groupingBy(element -> (element - 1) / YOUR_NUMBER_OF_PIECES_PER_SUBLIST));
List<List<Integer>> subLists= new ArrayList<List<Integer>>(groups.values());
System.out.println("Number of sublists " + subLists.size());
这给你:
Number of sublists: 5
当与NUMBER_OF_PIECES_PER_SUBLIST = 200
一起运行时,这似乎是你的用例。
您可以使用IntStream.iterate()
来实现:
int sublistItems = 100;
List<List<Integer>> result = IntStream.iterate(0, i -> i + sublistItems)
.limit((list.size() + sublistItems - 1) / sublistItems)
.mapToObj(startIndex -> list.subList(startIndex, Math.min(startIndex + sublistItems, list.size())))
.collect(Collectors.toList());
如果您使用的是Java 9或更高版本,则可以将其简化为:
int sublistItems = 100;
List<List<Integer>> result = IntStream.iterate(0, i -> i < list.size(), i -> i + sublistItems)
.mapToObj(startIndex -> list.subList(startIndex, Math.min(startIndex + sublistItems, list.size())))
.collect(Collectors.toList());