一. 按固定大小分片
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,主要通过偏移量来实现的
*
* @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;
}
简化版
/**
* 将一个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;
}