How to distribute a list into sub-lists, keeping the original order of the elements?

后端 未结 2 1456
轮回少年
轮回少年 2021-01-15 10:19

How to split a list into a given number of lists, taking the elements in order and distributing them to the sub-lists (so not partitioning the list)?

I would like to

相关标签:
2条回答
  • 2021-01-15 11:01

    If the source list supports efficient random access, like ArrayList does, you can use

    IntStream.range(0, source.size()).boxed()
      .collect(groupingBy(i->i%listCount, LinkedHashMap::new, mapping(source::get, toList())));
    

    e.g.

    List<Integer> source=IntStream.range(0, 20).boxed().collect(toList());
    System.out.println(source);
    int listCount=5;
    
    Map<Integer, List<Integer>> collect = IntStream.range(0, source.size()).boxed()
      .collect(groupingBy(i->i%listCount, LinkedHashMap::new, mapping(source::get, toList())));
    // in case it really has to be a List:
    List<List<Integer>> result=new ArrayList<>(collect.values());
    
    result.forEach(System.out::println);
    
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    [0, 5, 10, 15]
    [1, 6, 11, 16]
    [2, 7, 12, 17]
    [3, 8, 13, 18]
    [4, 9, 14, 19]
    
    0 讨论(0)
  • 2021-01-15 11:13

    Something like this could put all your lists into a map, then you just need to get the sub-lists out of the map

    int count = 0;
    Map<Integer, List<Integer>> mapLists = list.stream()
                                .peek(i -> count ++)
                                .collect(Collectors.groupingBy(i -> count % numOfSubLists))
    

    Another way using Guava

    https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Lists.html#partition(java.util.List,%20int)

    List<List<Integer>> lists = Lists.partition(list, noOfPartitions);
    
    0 讨论(0)
提交回复
热议问题