Java 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

结果:

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

不过这样做不到均分,下面介绍均分的方法

2.将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;
    }

--------------------- 本文来自 扎克伯哥 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/zhaohansk/article/details/77411552?utm_source=copy

猜你喜欢

转载自blog.csdn.net/weixin_41167961/article/details/82969991