package utils;
import java.util.ArrayList;
import java.util.List;
/**
* 集合拆分
*/
public class ListUtils {
/**
* 将一组数据平均分成n组
*
* @param source 要分组的数据源
* @param n 平均分成n组
* @param <T>
* @return
*/
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;
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;
}
/**
* 将一组数据固定分组,每组n个元素
* @param source 要分组的数据源
* @param n 每组n个元素
* @param <T>
* @return
*/
public static <T> List<List<T>> fixedGrouping(List<T> source, int n) {
if (null == source || source.size() == 0 || n <= 0)
return null;
List<List<T>> result = new ArrayList<List<T>>();
int sourceSize = source.size();
int size = (sourceSize % n) == 0 ? (sourceSize / n) : ((source.size() / n) + 1);
for (int i = 0; i < size; i++) {
List<T> subset = new ArrayList<T>();
for (int j = i * n; j < (i + 1) * n; j++) {
if (j < sourceSize) {
subset.add(source.get(j));
}
}
result.add(subset);
}
return result;
}
/**
* 将一组数据固定分组,每组n个元素
*
* @param source 要分组的数据源
* @param n 每组n个元素
* @param <T>
* @return
*/
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;
}
/*
* List分割
*/
public static List<List<String>> groupList(List<String> list) {
List<List<String>> listGroup = new ArrayList<List<String>>();
int listSize = list.size();
//子集合的长度
int toIndex = 2;
for (int i = 0; i < list.size(); i += 2) {
if (i + 2 > listSize) {
toIndex = listSize - i;
}
List<String> newList = list.subList(i, i + toIndex);
listGroup.add(newList);
}
return listGroup;
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
// List<List<String>> lists = groupList(list);
List<List<String>> lists = fixedGrouping2(list, 3);
System.out.println("list:" + list.toString());
System.out.println(lists);
}
}
09-09
2151
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)