JAVA数组分段的两种方法
- 分隔数组 根据段数分段
- 分隔数组 根据每段数量分段
public static<T> List<List<T>> subListBySegment(List<T> data, int segments) {
List<List<T>> result = new ArrayList<>();
int size = data.size();
if (size > 0 && segments > 0) {
int count = size / segments;
List<T> cutList = null;
for (int i = 0; i < segments; i++) {
if (i == segments - 1) {
cutList = data.subList(count * i, size);
} else {
cutList = data.subList(count * i, count * (i + 1));
}
result.add(cutList);
}
} else {
result.add(data);
}
return result;
}
public static<T> List<List<T>> subListByCount(List<T> data, int count) {
List<List<T>> result = new ArrayList<>();
int size = data.size();
if (size > 0 && count > 0) {
int segments = size / count;
segments = size % count == 0 ? segments : segments + 1;
List<T> cutList = null;
for (int i = 0; i < segments; i++) {
if (i == segments - 1) {
cutList = data.subList(count * i, size);
} else {
cutList = data.subList(count * i, count * (i + 1));
}
result.add(cutList);
}
} else {
result.add(data);
}
return result;
}