List集合分片

List集合分片处理

使用场景

当集合过大,单次处理数据对数据库造成压力时,必须考虑分批分片处理数据。比如 Oracle数据库中IN参数个数不能超过1000 ,这时可以把参数进行分批处理。当然这种情况也可 用表关联代替IN:.在where条件中使用子查询,如“select * from b where c in (select d from e …)” 或者 可以拆分sql用 where id in (1, 2, …, 999) or id in (1000, …)这种方法解决 。本文则侧重讲解如何分片集合。

代码分析

public class SubList {

	public static void main(String[] args) {
		
		 String [] str = {"a1","b2","c3","d4","e5","f6","g7","h8","i9","j10","k11","L12","m13"};
		 List<String> list  = Arrays.asList(str);
		 List<List<String>> splitList = splitList(list, 6);
		 splitList.stream().forEach(System.out::println);
		
	}

	/**
	 * 指定大小,分割集合,将集合按照规定个数分为n个部分
	 */
	public static <T> List<List<T>> splitList(List<T> list, int length){
		if (list.isEmpty() || list == null || length < 1) {
			return Collections.emptyList();
		}
		//result 最终分片后结果
		List<List<T>> result = new ArrayList<List<T>>();
		 
		int size = list.size();
		System.out.println("分片前list大小: " + size);
		//count分片大小
		int count = (size + length -1) / length;
		System.out.println("每片大小为 " + length + ";共分为 " + count +" 片");
		for (int i = 0; i < count; i++) {
			List<T> subList = list.subList(i*length, (i+1)*length > size ? size : (i+1)*length);
			result.add(subList);
		}
		return result;
	}
}

输出结果:

分片前list大小: 13
每片大小为 6;共分为 3 片
[a1, b2, c3, d4, e5, f6]
[g7, h8, i9, j10, k11, L12]
[m13]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值