Java 8 partition list

后端 未结 5 2200
一个人的身影
一个人的身影 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 15:50

    That can be done easily using the subList() method:

    List collection = new ArrayList<>(21);
    // fill collection
    int chunkSize = 10;
    List> lists = new ArrayList<>();
    for (int i = 0; i < collection.size(); i += chunkSize) {
        int end = Math.min(collection.size(), i + chunkSize);
        lists.add(collection.subList(i, end));
    }
    

提交回复
热议问题