1. 场景
在数据库批量操作时,有可能数据量过大,不能一次性操作,所以需要将大集合拆分为多个小集合进行多次操作文章来源地址https://www.toymoban.com/news/detail-669781.html
2. 拆分集合方法(写了三种)
import com.google.common.collect.Lists;
import com.xin.demo.fastjsondemo.FastJsonFormatPrintUtils;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PartitionListDemo {
private static final int PARTITION_SIZE = 10;
public static void main(String[] args) {
// 大集合
List<String> list = new ArrayList<>();
for (int i = 0; i < 33; i++) {
list.add("xinliushijian" + i);
}
// 方法1 guava工具
List<List<String>> partitionList = Lists.partition(list, PARTITION_SIZE);
FastJsonFormatPrintUtils.formatPrint(partitionList);
System.out.println("===============");
// 方法2 stream流实现
List<List<String>> partitionList1 = partList1(list, PARTITION_SIZE);
FastJsonFormatPrintUtils.formatPrint(partitionList1);
// 方法3 普通方法实现
partList2(list, PARTITION_SIZE);
}
public static <T> List<List<T>> partList1(List<T> list, int size) {
if (CollectionUtils.isEmpty(list) || size < 1) {
return new ArrayList<>();
}
List<List<T>> partList = IntStream.range(0, list.size())
.boxed()
.collect(Collectors.groupingBy(index -> index / size))
.values()
.stream()
.map(indices -> indices.stream().map(list::get).collect(Collectors.toList()))
.collect(Collectors.toList());
return partList;
}
public static <T> List<List<T>> partList2(List<T> list, int size) {
if (CollectionUtils.isEmpty(list) || size < 1) {
return new ArrayList<>();
}
List<List<T>> allPartList = new ArrayList<>();
for (int i = 0; i < list.size(); i+=size) {
if (i + size > list.size()) {
size = list.size() - i;
}
List<T> parList = list.subList(i, i + size);
allPartList.add(parList);
}
FastJsonFormatPrintUtils.formatPrint(allPartList);
return allPartList;
}
}
3. 格式化打印方法
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.JSON;
public class FastJsonFormatPrintUtils {
public static void formatPrint(Object object) {
String pretty = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
System.out.println(pretty);
}
}
文章来源:https://www.toymoban.com/news/detail-669781.html
到了这里,关于大集合拆分成多个小集合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!