Divide the List into arbitrary numbers

Conclusion

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>

Usage example (1)

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]

Usage example (2)

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]

Background

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.

Recommended Posts

Divide the List into arbitrary numbers
Divide into arbitrary numbers from the latitude and longitude of north, south, east and west
Divide the post into 3 rows (each_slice method)
Make rational numbers into decimal numbers, make decimal numbers into rational numbers