Java List Partition partition(final List list, final int length)

Here you can find the source of partition(final List list, final int length)

Description

Partitions a list of objects into smaller lists

License

Open Source License

Parameter

Parameter Description
list list to partition
length length of each partition
T list type

Return

list of lists

Declaration

public static <T> List<List<T>> partition(final List<T> list, final int length) 

Method Source Code


//package com.java2s;
/*/*from   w  w w . j a v  a  2s .c o  m*/
 * jGnash, a personal finance application
 * Copyright (C) 2001-2019 Craig Cavanaugh
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Partitions a list of objects into smaller lists
     * @param list list to partition
     * @param length length of each partition
     * @param <T> list type
     * @return list of lists
     */
    public static <T> List<List<T>> partition(final List<T> list, final int length) {

        final List<List<T>> parts = new ArrayList<>();

        for (int i = 0; i < list.size(); i += length) {
            parts.add(new ArrayList<>(list.subList(i, Math.min(list.size(), i + length))));
        }
        return parts;
    }
}

Related

  1. partition(final List items, final int size)
  2. partition(List list, Integer batchSize)
  3. partition(List all, int partitionSize)
  4. partition(List a, int lower, int upper)
  5. partition(List items, int slices)