如何使用Stream API将数组分成子数组。

3

我有一个大小为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编写代码。提前感谢!


你还记得列表从索引 0 开始,对吧? - Sharon Ben Asher
所以范围是0-99,100-199等等,对吗? - Sharon Ben Asher
@SharonBenAsher 你可能想把这两个问题合并成一个评论。现在看起来很傻。 (标记我的评论以删除,这样当你完成后它就会被删除)。 - ZF007
是的,@SharonBenAsher,实际上对于第一个子列表,元素数量将从0到100,即101个元素。 - Hasnain Ali Bohra
但是.subList(0,100)仅有100个元素。而.subList(101,200)将有99个元素。 - Holger
4个回答

5

那么,关于这个问题:

  List<List<Integer>> result = IntStream.range(0, list.size() / 100)
         .mapToObj(index -> list.subList(index * 100, index * 100 + 100))
         .collect(Collectors.toList());

2
你可以使用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 运行时,它代表每个子列表的数量为200。最初的回答。

1
@ltFreak 我不确定partitioningBy适用于我的情况,因为partitioningBy的用例是根据提供的谓词将列表分成两部分。 - Hasnain Ali Bohra
@HasnainAliBohra,你是对的,我扩展了我的答案。 - ItFreak

0
你可以使用 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());

0
要使用Stream API数组,您需要使用StreamSupportSpliteratorArrays提供了创建Spliterator的实用方法。
例如:
int[] array = new int[1000];
StreamSupport.stream(Arrays.spliterator(array, 0, 100), false)
  .forEach(e -> {});
StreamSupport.stream(Arrays.spliterator(array, 100, 200), false)
  .forEach(e -> {});

注意 - 这是从零开始的索引,起始索引是包含的,而结束索引是不包含的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接