List分片处理

写代码时有时需要将List按XX大小分片,或者均分成几个List,此时最好不要new很多新的List然后向里面add,这样做效率很低,下面介绍两种高效分片的方法。

一. 按固定大小分片

1.直接用guava库的partition方法即可。

import com.google.common.collect.Lists;

public class ListsPartitionTest {
    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));
    }
}


//  [[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 4, 5, 6, 7, 7, 6, 6, 6, 6], [6, 66]]

2.使用apache.commons.collection实现

import org.apache.commons.collections4.ListUtils;
public class ListsPartitionTest2 {
    public static void main(String[] args) {
       List<String> intList = 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(ListUtils.partition(intList, 3));
    }
}


// [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 4], [5, 6, 7], [7, 6, 6], [6, 6, 6], [66]]

可以看出以上两个方法使用情况相同,都是有两个参数:partition(要切分的list,每个list的大小);这样需要制定切割后每个list的大小。那么怎么平均分配呢,这些集合类中好像没有现成的方法,只能自己手写了,从网上看到了这样一个方法:

二、将list 平均分成n份

    /**
     * 将一个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;
    }

这个方法也是两个参数,averageAssign(要平均分的list,要平均分成几份)。可见,这种方法只是规定了分成几份,具体分后的list的大小是平均分决定的。

自己的需求其实不需要平均分,自己改写了一个简化版的方法:

    /**
     * 将一个list分成n个list, 
     *   每个list放的是商的个数,最后除数的余数放入最后一个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 number = source.size() / n;  //商
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (i == n - 1) {
                value = source.subList(i * number, source.size());
            } else {
                value = source.subList(i * number, (i + 1) * number);
            }
            result.add(value);
        }
        return result;
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值