How to split where the list values are different

Asked 1 years ago, Updated 1 years ago, 110 views

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

2022-09-30 21:35

2 Answers

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;
}


2022-09-30 21:35

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]]


2022-09-30 21:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.