Java 將List平均分成若干個集合__集合

來源:互聯網
上載者:User

1.初衷是由於調用銀行介面的批量處理介面時,每次最多隻能處理500條資料,但是當資料總數為510條時。我又不想第一次調用處理500條,第二次調用處理10條資料,我想要的是每次處理255條資料。下面展示的是我的處理方法

2.寫了一個簡單的ListUtils:

package com.example.springboottest.common.util;import java.util.ArrayList;import java.util.Collections;import java.util.List;/** * List 工具類 * @author Neo  * @date 2018年4月16日13:13:37 */public class ListUtils {    /**     * 將一個List均分成n個list,主要通過位移量來實現的     *     * @param source 源集合     * @param limit 最大值     * @return     */    public static <T> List<List<T>> averageAssign(List<T> source, int limit) {        if (null == source || source.isEmpty()) {            return Collections.emptyList();        }        List<List<T>> result = new ArrayList<>();        int listCount = (source.size() - 1) / limit + 1;        int remaider = source.size() % listCount; // (先計算出餘數)        int number = source.size() / listCount; // 然後是商        int offset = 0;// 位移量        for (int i = 0; i < listCount; i++) {            List<T> value;            if (remaider > 0) {                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);                remaider--;                offset++;            } else {                value = source.subList(i * number + offset, (i + 1) * number + offset);            }            result.add(value);        }        return result;    }    public static void main(String[] args) {        List list = new ArrayList();        for (int i = 0; i < 65; i++) {            list.add(i);        }        List<List> result = averageAssign(list, 15);        result.forEach(l -> {            l.forEach(i ->                    System.out.print(i + "\t")            );            System.out.println();        });        System.out.println("====================================================");        result = averageAssign(list, 20);        result.forEach(l -> {            l.forEach(i ->                    System.out.print(i + "\t")            );            System.out.println();        });    }}

3.展示一下測試結果:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.