java8 Stream 大数据量List分批处理切割

  1. java8 Stream 大数据量List分批处理
//按每3个一组分割
private static final Integer MAX_NUMBER = 3;

public static void main(String[] args) {
      List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
      int limit = countStep(list.size());
      //方法一:使用流遍历操作
      List<List<Integer>> mglist = new ArrayList<>();
      Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> {
          mglist.add(list.stream().skip(i * MAX_NUMBER).limit(MAX_NUMBER).collect(Collectors.toList()));
      });

      System.out.println(mglist);

      //方法二:获取分割后的集合
      List<List<Integer>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(a -> list.stream().skip(a * MAX_NUMBER).limit(MAX_NUMBER).parallel().collect(Collectors.toList())).collect(Collectors.toList());
      
      System.out.println(splitList);
}
	
/**
* 计算切分次数
*/
private static Integer countStep(Integer size) {
	return (size + MAX_NUMBER - 1) / MAX_NUMBER;
}
  1. 使用google guava对List进行分割
//使用guava对list进行分割
List<User> users = userService.findAll();
//按每50个一组分割
List<List<User>> parts = Lists.partition(users, 50);
parts.stream().forEach(list -> {
    process(list);
});
  1. 使用apache common collection
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
List<List<Integer>> subs = ListUtils.partition(intList, 3);
  1. java 手写将一个List等分成n个list
public static <T> List<List<T>> averageAssign(List<T> source, int n) {
    List<List<T>> result = new ArrayList<>();
    int remainder = source.size() % n;  //(先计算出余数)
    int number = source.size() / n;  //然后是商
    int offset = 0;//偏移量
    for (int i = 0; i < n; i++) {
        List<T> value;
        if (remainder > 0) {
            value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
            remainder--;
            offset++;
        } else {
            value = source.subList(i * number + offset, (i + 1) * number + offset);
        }
        result.add(value);
    }
    return result;
}

转载于:https://blog.csdn.net/fzy629442466/article/details/84765070

    原文作者:yinni11
    原文地址: https://blog.csdn.net/yinni11/article/details/88288021
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞