Use org.apache.commons.collections4.ListUtils # partition ().
Javadoc https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ListUtils.html#partition-java.util.List-int-
Maven https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.4
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
Specify the maximum number of elements per one
List<String> list0 = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
List<List<String>> lists = ListUtils.partition(list0, 3);
for (List<String> list : lists) {
System.err.println(list);
}
[aaa, bbb, ccc]
[ddd, eee, fff]
[ggg]
Specify how many you want to divide
List<String> list0 = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
List<List<String>> lists = ListUtils.partition(list0, list0.size() / 2 + 1);
for (List<String> ll : lists) {
System.err.println(ll);
}
[aaa, bbb, ccc, ddd]
[eee, fff, ggg]
I made a similar method by myself and completed it, but I realized that "This is in Commons !?" and came to the discovery orz.
that's all.