How to split where the list values are different
Currently
in List<Integer>
{1,1,2,2,3,3,3,3,3}
and so on.
Is it possible to divide this between 1 and 2 and between 2 and 3 and return List<List>Integer>>
?
Results I want
{
[1, 1, 1],
[2, 2],
[3, 3, 3, 3]
}
The language is Java, Kotlin.
java kotlin
If you do it without any particular ingenuity, it will look like this.
private List<List<Integer>convert(List>Integer>originalList){
if(originalList==null){
return null;
}
List<List<Integer>>newList=newArrayList<();
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;
}
It's not correct in the sense of split, but how about groupingBy yourself
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]]
© 2024 OneMinuteCode. All rights reserved.