場景: 把一個List集合按指定長度分割成組
1. 手動實現(xiàn) (已經(jīng)自測通過)
private List<List<String>> splitList(List<String> list , int groupSize){
int length = list.size();
// 計算可以分成多少組
int num = ( length + groupSize - 1 )/groupSize ; // TODO
List<List<String>> newList = new ArrayList<>(num);
for (int i = 0; i < num; i++) {
// 開始位置
int fromIndex = i * groupSize;
// 結(jié)束位置
int toIndex = (i+1) * groupSize < length ? ( i+1 ) * groupSize : length ;
newList.add(list.subList(fromIndex,toIndex)) ;
}
return newList ;
}
*注:TODO 標(biāo)注部分是個小技巧,正常情況下計算能拆分多少組是:
length % groupSize == 0 ? length / groupSize : length / groupSize +1
這里使用 ( length + groupSize - 1 ) / groupSize則減少運算了。
2. 使用guave實現(xiàn)
import com.google.common.collect.Lists;
private List<List<String>> splitList(List<String> list , int groupSize){
return Lists.partition(list, groupSize); // 使用guava
}
注:如果要了解其它工具類的實現(xiàn)此功能,可以看最后兩篇引用的文章
- Java 將List按照指定大小分段
- Java List按大小分片,平均切分
- Partition a List in Java [推薦]
- java 將list按照指定數(shù)量分成小list 注:有點像 Partition a List in Java 的翻譯