java 把list分成5份_Java 实现将List平均分成若干个集合

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 List> averageAssign(Listsource, int limit) {

if (null == source || source.isEmpty()) {

return Collections.emptyList();

}

List> 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++) {

Listvalue;

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);

}

Listresult = 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.展示一下测试结果:

6a62923f087c91c8118556d0699f0003.png

补充知识:Java8 Lambda 分割List

我就废话不多说了,大家还是直接看代码吧~

/**

* @author caishen

* @version 1.0

* @className CollectionUtils

* @date 2019/5/23 11:54

* 自分で書いたコードの各行を担当する

* @dis 切割list工具类

**/

public class CollectionUtils {

public static List> divide(Listorigin , 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平均分成若干个集合就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值