有没有办法在 Java 8 中使用流合并列表中的重复数字?

Ani*_*h N 6 java java-8 java-stream

例如#1 [1, 1, 1, 2, 22, 35, 35, 120, 320]==>>[3, 2, 22, 70, 120, 320]

请注意如何将重复的连续 1 和 35 分别合并为 3 和 70

例如#2 [1,1,3,1,1]==>>[2,3,2]

Eug*_*ene 8

Stream.of(1, 1, 1, 2, 22, 35, 35, 120, 320)
          .collect(Collectors.toMap(
              Function.identity(),
              Function.identity(),
              Integer::sum,
              LinkedHashMap::new
          ))
          .values()
          .forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

如果您发表评论,您将需要一个自定义收集器,实际上:

static class Custom implements Collector<Integer, List<Integer>, List<Integer>> {

    private Integer match;

    @Override
    public Supplier<List<Integer>> supplier() {
        return ArrayList::new;
    }

    @Override
    public BiConsumer<List<Integer>, Integer> accumulator() {
        return (list, x) -> {
            int lastIndex = list.size() - 1;
            if (match != null && match.equals(x)) {
                list.set(lastIndex, list.get(lastIndex) + x);
            } else {
                match = x;
                list.add(x);
            }
        };
    }

    @Override
    public BinaryOperator<List<Integer>> combiner() {
        return (left, right) -> {
            throw new RuntimeException("Not for parallel");
        };
    }

    @Override
    public Function<List<Integer>, List<Integer>> finisher() {
        return Function.identity();
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Set.of();
    }
}
Run Code Online (Sandbox Code Playgroud)

用法是:

public static void main(String[] args) {
    Stream.of(1, 1, 3, 1, 1)
          .collect(new Custom())
          .forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)

  • 但这不起作用: [0,0,0,0, 1, 1, 1, 0, 0, 0] =&gt; [0, 3, 0] (4认同)