java List.subList()方法使用

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++;
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值