1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

List を任意の数に分割する(Listを任意の要素数ごとに分割する)

Last updated at Posted at 2020-05-05

#結論

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>

##利用例(1)
一つあたりの最大の要素の数を指定する

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]

##利用例(2)
いくつに分割したいかを指定する


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]

経緯

同様のメソッドを自作して完成したのですが「これはCommonsにあるのでは!?」と気づいて発見に至りましたorz。

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?