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.展示一下測試結果: