Is there a way to coalesce repeated numbers in a list using streams in Java 8?

后端 未结 3 1088
长发绾君心
长发绾君心 2021-02-06 12:06

e.g.#1 [1, 1, 1, 2, 22, 35, 35, 120, 320] ==>> [3, 2, 22, 70, 120, 320]

note how repeated consecutive 1\'s and 35\'s are coalesced to 3 and 70

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 13:05

    Why bother using streams when you can do it with a simple for loop and an if-else block?

       List list = List.of(0, 0, 0, 0, 1, 1, 1, 0, 0, 0);
       List result = new ArrayList<>();
       Integer curr = list.get(0);
       Integer sum = 0;
       for(Integer i : list){
           if(i.equals(curr)){
               sum += i;
           }
           else{
               result.add(sum);
               sum = i;
               curr = i;
           }
       }
       result.add(sum);
       System.out.println(result);
    

提交回复
热议问题