一个List按照数量分隔成多个List

1. 将一个List平均分割成n个List

例如:list中有11条数据,分成3个(n)list,每一个list平均三条还剩余两条,会先把前两个list分别加一条(0*3 + 1, 1*3 + 1)、(1*3 + 1, 2*3 + 1)
其中offset=2为记录不能平均分配的数量,最后一个list会按照(2*3+2,3*3+2)分配,其中的2即为offset
如果整除没有余数,循环i到n,每次分配(i*(总数/n), (i+1)*(总数/n))

source为 要分割的List, n为 要分割多少个新的List

public static <T> List<List<T>> averageAssign(List<T> source, int n) {
	List<List<T>> result = new ArrayList<List<T>>();
	int remainder = source.size() % n;  //余数
	int number = source.size() / n;  //商
	int offset = 0;//
	for (int i = 0; i < n; i++) {
	    List<T> value = null;
	    //当余数不为0,循环把余数循环加入到每个组中
	    if (remainder > 0) {
	        value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
	        remainder--;
	        offset++;
	    } else {
	        value = source.subList(i * number + offset, (i + 1) * number + offset);
	    }
	    result.add(value);
	}
	return result;
}

2. 将一个List按照每个新的List有n个元素
已知总条数m和每个新的List的元素个数n,j = m/n, j为平均分配List的个数(i*n, (i+1)*n),如果(m%n != 0),那么将剩余的元素放到最后一个List中(j*n,j*n + m%n)

public static <T> List<List<T>> fixedGrouping2(List<T> source, int n) {

    if (null == source || source.size() == 0 || n <= 0)
        return null;
    List<List<T>> result = new ArrayList<List<T>>();
    int remainder = source.size() % n;
    int size = (source.size() / n);
    for (int i = 0; i < size; i++) {
        List<T> subset = null;
        subset = source.subList(i * n, (i + 1) * n);
        result.add(subset);
    }
    if (remainder > 0) {
        List<T> subset = null;
        subset = source.subList(size * n, size * n + remainder);
        result.add(subset);
    }
    return result;
}

转载:https://blog.csdn.net/a_limingfei/article/details/81559744

猜你喜欢

转载自blog.csdn.net/shy415502155/article/details/90473824
今日推荐