国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

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

瀏覽:6日期:2022-08-26 18:46:21

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; import com.google.common.collect.Lists;/** * 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(); }); System.out.println('===================================================='); // Guava 實現不平均分組 result = Lists.partition(list ,100);result.forEach(l -> { l.forEach(i -> System.out.print(i + 't') ); System.out.println(); }); }}

3.展示一下測試結果:

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

補充知識:Java8 Lambda 分割List

我就廢話不多說了,大家還是直接看代碼吧~

/** * @author caishen * @version 1.0 * @className CollectionUtils * @date 2019/5/23 11:54 * 自分で??い駿暢`ドの各行を擔當する * @dis 切割list工具類 **/public class CollectionUtils { public static <T> List<List<T>> divide(List<T>origin , int size){ if(Assert.isEmpty(origin)){ return Collections.emptyList(); } int block = (origin.size() + size -1) / size; return IntStream.range(0,block).boxed().map(i->{ int start = i*size; int end = Math.min(start + size,origin.size()); return origin.subList(start,end); }).collect(Collectors.toList()); } public static void main(String[] args) { System.out.println(divide(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 3)); }}

以上這篇Java 實現將List平均分成若干個集合就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 哈密市| 郁南县| 东丰县| 益阳市| 博湖县| 漳州市| 葫芦岛市| 北安市| 北海市| 广安市| 德昌县| 巍山| 太原市| 会昌县| 荣成市| 乐清市| 定远县| 镇巴县| 庆城县| 安陆市| 郯城县| 寿光市| 灯塔市| 祁连县| 石家庄市| 安西县| 延长县| 富裕县| 德清县| 茌平县| 嘉定区| 龙州县| 宣恩县| 竹溪县| 惠东县| 滕州市| 汕头市| 定襄县| 垫江县| 萨迦县| 平定县|