集合(六)集合分片

在某些场景中,需要批量执行数据,可以通过数据库分页查询,也可以通过java来对集合进行分页。将list(或其他集合)拆分成多份,java传统的集合操作中并没有这样的方法。常见方法有:

1、手动分片:

/**
     * 将一个list均分成n个list,主要通过偏移量来实现的
     *
     * @param source
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<List<T>>();
        int remaider = source.size() % n;  //(先计算出余数)
        int number = source.size() / n;  //然后是商
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            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;
    }

2、google guava分片: 

import com.google.common.collect.Lists;
public class ListsPartitionTest1 {
    public static void main(String[] args) {
        List<String> ls = Arrays.asList("1,2,3,4,5,6,7,8,9,1,2,4,5,6,7,7,6,6,6,6,6,66".split(","));
        System.out.println(Lists.partition(ls, 20));
    }
}


再如:

import com.google.common.collect.Lists;

import java.util.Arrays;
import java.util.List;

public class ListsTest {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        // 按大小 2 拆分
        List<List<Integer>> listPartitionList = Lists.partition(list, 2);

        System.out.println("原 List:");
        System.out.println(list);

        System.out.println("拆分后:");
        for (List<Integer> partition: listPartitionList) {
            System.out.println(partition);
        }
    }

}



原 List:
[1, 2, 3, 4, 5]
拆分后:
[1, 2]
[3, 4]
[5]

 

3、apache commons collections分片:

import org.apache.commons.collections4.ListUtils;
public class ListsPartitionTest2 {
    public static void main(String[] args) {
      List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
      System.out.println(ListUtils.partition(intList, 3));
    }
}

4、使用Java8 stream流 partition by,partitioningBy是一种特殊的分组,只会分成两组

 List<Integer> nums = Lists.newArrayList(1,1,8,2,3,4,5,6,7,9,10);
Map<Boolean,List<Integer>> numMap= numList.stream().collect(Collectors.partitioningBy(num -> num > 5));
        System.out.println(numMap);

{false=[2, 3, 4, 5], true=[8, 6, 7, 9, 10]}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_t_y_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值