devide List by size and return list of list - Java java.util

Java examples for java.util:List Operation

Description

devide List by size and return list of list

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 ava  2  s  . c  o  m*/

        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