参考:
手写1
java
private List<List<String>> splitList(List<String> list, int listSize){
if (null === list || 0 === listSize) {
return new ArrayList();
}
int length = list.size();
int num = ( length + listSize- 1 )/listSize;
List<List<String>> newList = new ArrayList<>(num);
for (int i = 0; i < num; i++) {
int fromIndex = i * listSize;
int toIndex = (i+1) * listSize< length ? ( i+1 ) * listSize: length ;
newList.add(list.subList(fromIndex, toIndex)) ;
}
return newList ;
}
手写2
java
public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
List<List<T>> subLists = new ArrayList<>();
for (int i = 0; i < list.size(); i += splitSize) {
int end = Math.min(i + splitSize, list.size());
subLists.add(list.subList(i, end));
}
return subLists;
}
手写3
java
public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
return IntStream.range(0, (list.size() + splitSize - 1) / splitSize)
.mapToObj(i -> list.subList(i * splitSize, Math.min((i + 1) * splitSize, list.size())))
.collect(Collectors.toList());
}
Guava
xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>12.0.1</version>
</dependency>
java
Lists.partition(list, listSize)
apache的collections4
xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
java
ListUtils.partition(OLD_LIST, 3);
hutool
xml
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.14</version>
</dependency>
java
ListUtil.partition(OLD_LIST, 3);