Java批量写入
<h5>集合批量写入通用算法</h5>
<pre><code>package com.example.demo;
import java.util.ArrayList;
import java.util.List;
public class BatchTest {
/**
* 批量写入
*
* @param args
*/
public static void main(String[] args) {
List<String> list = reterList();
int j = 0;
//批量写入数据量
int batchNum = 10;
int batchNum_bak = 10;
int total = list.size();
while (true) {
list.subList(j, j = j + batchNum).forEach(x -> {
//执行业务逻辑
System.out.println(x);
});
batchNum = ((total - j) % batchNum_bak) == 0 ? batchNum_bak : ((total - j) % batchNum_bak);
if (j >= total) {
break;
}
}
}
/**
* 造数据
*
* @return
*/
public static List<String> reterList() {
List<String> list = new ArrayList<>();
for (int i = 0; i < 103; i++) {
list.add(i + "");
}
return list;
}
}
</code></pre>
<h5>写法二</h5>
<pre><code> /**
* 批量处理
*/
int index = 0;
int num = 30;
for (; ; ) {
if(total<=num){
num=total;
}
list.subList(index, index = index + num).forEach(x -> {
//执行业务逻辑
System.out.println(x);
});
num = (total - index) < num ? (total - index) : num;
if (index >= total) {
break;
}
}</code></pre>
<h5>写法二Demo:</h5>
<pre><code>public class App {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 105; i++) {
list.add(i);
}
batchOperate(list);
}
/**
* 批量操作算法
*/
public static void batchOperate(List<Integer> list) {
int total = list.size();
int index = 0;
int num = 10;
//统计循环次数
int count = 0;
for (; ; ) {
count++;
System.out.println("第:" + count + "次");
if (total <= num) {
num = total;
}
list.subList(index, index = index + num).forEach(x -> {
//执行业务逻辑
System.out.println(x);
});
num = (total - index) < num ? (total - index) : num;
if (index >= total) {
break;
}
}
}
}</code></pre>