Java 8 partition list

后端 未结 5 2202
一个人的身影
一个人的身影 2021-02-18 15:37

Is it possible to partition a List in pure Jdk8 into equal chunks (sublists).

I know it is possible using Guava Lists class, but can we do it with pure Jdk? I don\'t wan

5条回答
  •  伪装坚强ぢ
    2021-02-18 16:10

    Try using this code, it uses Java 8:

    public static Collection> splitListBySize(List intList, int size) {
    
        if (!intList.isEmpty() && size > 0) {
            final AtomicInteger counter = new AtomicInteger(0);
            return intList.stream().collect(Collectors.groupingBy(it -> counter.getAndIncrement() / size)).values();
        }
        return null;
    }
    

提交回复
热议问题