java 的List有个很有意思的subList()方法,用于将List快速拆分为多个子List,避免使用for循环遍历list ,在有些场景(例如批量读取部分list,ibatis批量插入)很适合使用,
代码如下
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Test {
public static void main(String[] args) throws Exception {
Test test = new Test();
//每次要从list获取的数量
int pageSize = 10;
test.testListSubMethod(10);
}
/**
* 测试list的subList方法,快速拆分list
* @param pageSize 每次拆分的数量
*/
public void testListSubMethod(int pageSize) {
//要生成的随机数字数量
int all = 137;
//记录获取次数
int page = 1;
//测试List
List<String> testList = new ArrayList<String>();
//生成随机数字,推送到List中
for (int i = 1; i <= all; i++) {
Random r = new Random();
double d = r.nextDouble()*1.5+100;
d= (d-100)*100;
testList.add(String.valueOf(Math.round(d)));
}
System.out.println(testList.size() + ":" + testList.toString());
int total = testList.size();
int fromIndex = 0;
int toIndex = 0;
List<String> tmpList = null;
if (testList == null || testList.size() == 0) {
return;
}
while (true) {
tmpList = new ArrayList<String>();
fromIndex = (page - 1) * pageSize;
toIndex = page * pageSize;
if (page * pageSize >= total - 1) {
toIndex = total;
}
tmpList = testList.subList(fromIndex, toIndex);
System.out.println(tmpList.size() + ":" + tmpList.toString());
//如果超过LIST大小,退出,反之显示下一个子list
if (toIndex == total) {
break;
} else {
page++;
}
}
}
}