有没有一种方法可以使用Java 8中的流来合并列表中的重复数字? [英] Is there a way to coalesce repeated numbers in a list using streams in Java 8?

查看:200
本文介绍了有没有一种方法可以使用Java 8中的流来合并列表中的重复数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

e.g.#2 [1,1,3,1,1] ==>> [2,3,2]

推荐答案

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

在您发表评论的情况下,实际上需要一个自定义收集器:

In the case the you posted a comment, you would need a custom collector, actually:

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

用法为:

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

这篇关于有没有一种方法可以使用Java 8中的流来合并列表中的重复数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆