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

后端 未结 3 1081
长发绾君心
长发绾君心 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:00

    Here is an approach using a stack.

    public static List coalesce(List list) {
        Stack stack = new Stack<>();
        stack.addAll(list);
        List sums = new ArrayList<>();
        int sum = 0;
        while (!stack.isEmpty()) {
           int val = stack.pop();
           sum += val;
           if (!stack.isEmpty() && stack.peek() != val) {
              sums.add(0,sum);
              sum = 0;
           }
        }
        sums.add(0,sum);
        return sums;
    }
    

提交回复
热议问题