Listの値が違う所でsplitをする方法
現在List<Integer>
に
{1, 1, 1, 2, 2, 3, 3, 3, 3}
といった形で値が入っています。
これを 1 と 2 の間で、 2 と 3 の間それぞれで分割して、List<List<Integer>>
と返すことは出来ないのでしょうか。。?
ほしい結果
{
[1, 1, 1],
[2, 2],
[3, 3, 3, 3]
}
言語はJava,Kotlinを使用しています。
スタック・オーバーフローはプログラマーとプログラミングに熱心な人のためのQ&Aサイトです。すぐ登録できます。
登録してこのコミュニティに参加する特に工夫なくやれば、こんな感じですかね。
private List<List<Integer>> convert(List<Integer> originalList) {
if (originalList == null) {
return null;
}
List<List<Integer>> newList = new ArrayList<>();
Integer tmpNum = null;
List<Integer> tmpList = null;
for (Integer integer : originalList) {
if (tmpNum == null || integer.compareTo(tmpNum) != 0) {
tmpList = new ArrayList<>();
newList.add(tmpList);
}
tmpList.add(integer);
tmpNum = integer;
}
return newList;
}
splitという意味では正しくないですが、 groupingBy 自分
でどうでしょうか。
final List<Integer> nums = new Random().ints(10, 1, 4).boxed().collect(Collectors.toList());
System.out.println(nums); // [1, 2, 3, 3, 1, 2, 2, 1, 2, 3]
final Map<Integer, List<Integer>> group = nums.stream().collect(Collectors.groupingBy(Function.identity()));
System.out.println(group.values()); // [[1, 1, 1], [2, 2, 2, 2], [3, 3, 3]]
List<List<Integer>>
を作る方が簡単かもしれません。最初のリストがソートされている、もしくは同じ数値をまとめて良いことが条件ですが・・・