java切分List

public class MyListUtil {

    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<>();
        //(先計算出餘數)
        int remainder = source.size() % n;
        //而後是商
        int number = source.size() / n;
        //偏移量
        int offset = 0;
        for (int i = 0; i < n; i++) {
            List<T> value;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }

}
本文由博客一文多發平臺 OpenWrite 發佈! 我的公衆號《駭客與畫家》,歡迎關注
相關文章
相關標籤/搜索