Java批量處理數據


要求:共1000條數據,第一次批量插入100條,第二次批量插入101到200條,依次插入數據;

實現方式這里選擇了兩種常用的方式,都是使用List操作;

第一種實現思路如下:

<1> 原先存放數據的List為recordList,求出共需批量處理的次數;

<2> 新建一個List為list,循環后,將recordList的前maxValue條數據放到list里;

<3> 調用批量處理方法,調用recordList的removeAll方法將list中的數據從recordList中清除;

<4> 調用list.clear方法清除掉list本身的數據;

/** * 批量插入 例如:共1000條數據,第一次批量插入100條,第二次批量插入101到200條,依次插入數據; * * @param recordList * @param maxValue 批量處理的條數,如1000條 * @return
     */
    private void batchAddRecords(List<String> recordList, int maxValue) { List<String> list = new ArrayList<String>(); int size = recordList.size(); int total = size / maxValue; if (size % maxValue != 0) { total += 1; } for (int i = 0; i < total; i++) { if (i == total - 1) { maxValue = size - (i * maxValue); } for (int j = 0; j < maxValue; j++) { list.add(recordList.get(j)); } // 批量處理的方法
 print(list); recordList.removeAll(list); list.clear(); } }

 

第二種實現思路類似:

通過調用recordList的subList方法,將截取后的內容保存到list中,然后調用批量處理方法,最后調用list的clear方法將list和recordList中的這部分數據清除;

需注意的是:List的subList方法有點特殊,它操作的是list和原先list所引用的同一塊內存,所以需要注意些。

private void batchAddRecords2(List<String> recordList, int maxValue) { List<String> list = new ArrayList<String>(); int size = recordList.size(); int total = size / maxValue; if (size % maxValue != 0) { total += 1; } for (int i = 0; i < total; i++) { if (i == total - 1) { maxValue = size - (i * maxValue); } list = recordList.subList(0, maxValue); // 批量處理的方法
 print(list); list.clear(); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM