devide list by size - Java java.util

Java examples for java.util:List Operation

Description

devide list by size

Demo Code


//package com.java2s;
import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class Main {
    public static final <T> List<List<T>> devide(List<T> origin, int size) {
        if (origin == null || origin.isEmpty() || size <= 0) {
            return Collections.emptyList();
        }//w  w w .j  a  v  a2  s. c  om

        final int block = origin.size() / size
                + (origin.size() % size > 0 ? 1 : 0);

        List<List<T>> devidedList = new ArrayList<List<T>>(block);
        for (int i = 0; i < block; i++) {
            final int start = i * size;
            final int end = Math.min(start + size, origin.size());
            devidedList.add(new ArrayList<T>(origin.subList(start, end)));
        }
        return devidedList;
    }
}

Related Tutorials