Created
July 9, 2019 05:20
-
-
Save j3N0/254d37d0c1a04ffd82fe9e9814e05073 to your computer and use it in GitHub Desktop.
Stream() 切分List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment