java中List分片方法

java中List分片方法

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说java中List分片方法,希望能够帮助大家进步!!!

一. 按固定大小分片

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(","));
        log.info(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]]

二、将list 平均分成n份

/**
     * 将一个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;
    }
本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18234

发表评论