【问题标题】:Java 8 count objects with multiple valuesJava 8 计算具有多个值的对象
【发布时间】:2017-02-16 20:29:14
【问题描述】:

假设我有一个名为 Combination 的类,它由两个类型为简单枚举值的字段组成。

例子:

new Combination(Animal.DOG, Animal.CAT),

new Combination(Animal.CAT, Animal.APE),

new Combination(Animal.MOUSE, Animal.DOG)

我有一组组合,我想计算每只动物的总出现次数,以便示例输出如下所示:

DOG=2
CAT=2
MOUSE=1
APE=1

我已经尝试了不同的方法,但我还没有找到解决方案。在 java 8 中是否有任何简单的方法可以做到这一点?

提前致谢。

【问题讨论】:

  • 你可以从 for 循环开始了解算法
  • Combination 的访问器是什么?
  • 您尝试了哪些不同的方法?

标签: java lambda count java-stream


【解决方案1】:

这是一种方法:

Map<Animal, Long> counts = combinations.stream()
        .flatMap(c -> Stream.of(c.getFirst(), c.getSecond()))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

或者:

Map<Animal, Long> counts = Stream.concat(
            combinations.stream().map(Combination::getFirst),
            combinations.stream().map(Combination::getSecond))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    相关资源
    最近更新 更多