如何使用流API将数组划分为子数组

问题描述 投票:2回答: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的代码。提前致谢

java list java-8 java-stream
3个回答
4
投票

关于什么 :

  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一起运行时,这似乎是你的用例。


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());
© www.soinside.com 2019 - 2024. All rights reserved.