【问题标题】:Can you use a functor/functional programming to group a list in Java 7 (and count its elements per group)?您可以使用仿函数/函数式编程对 Java 7 中的列表进行分组(并计算每组的元素)吗?
【发布时间】:2017-05-21 17:18:39
【问题描述】:

您能否使用仿函数(例如 Google's GuavaApache's Commons Functorpre Java 8 将 List<TypeEnum> types = new ArrayList(Arrays.asList(TypeEnum.A, TypeEnum.B, TypeEnum.A)); 分组为 Map<TypeEnum, Integer> countPerType;

我正在尝试了解函数式编程,但不确定这种事情是否真的可行(因为我不只是映射集合值,而是尝试聚合)?

在命令式风格中,我会做这样的事情:

public Map<TypeEnum, Integer> countByGroup(List<TypeEnum> types) {
    Map<TypeEnum, Integer> countedTypes = new HashMap<>();
    for(TypeEnum type : types) {
        if(countedTypes.containsKey(type)) {
            countedTypes.put(type, countedTypes.get(type) + 1);
        } else {
            countedTypes.put(type, 1);
        }
    }
    return countedTypes;
}


编辑: 依赖副作用似乎有些不合适 - 或者它是如何完成的......?
Procedure<TypeEnum> count = new Procedure<TypeEnum>() {
public Map<TypeEnum, Integer> countPerType = null;

    @Override
    public void run(TypeEnum type) {
        if(countPerType.containsKey(type)) {
            countPerType.put(type, countPerType.get(type) + 1);
        } else {
            countPerType.put(type, 1);
        }
    }

    public Procedure<TypeEnum> init(Map<TypeEnum, Integer> countPerType) {
        this.countPerType = countPerType;
        return this;
    }
}.init(countPerType); // kudos http://stackoverflow.com/a/12206542/2018047

【问题讨论】:

  • 使用 Guava,您需要一个简单的Multiset,更具体地说是它的EnumMultiset 实现。 Multiset 是一种用于跟踪计数元素的数据结构。
  • Java 8 并不神奇,即 Stream API 由使用接口类型参数的普通 Java 代码组成。没有理由不应该在 Java8 之前的环境中工作。
  • 是的,我知道。正如我所说,我正在尝试使用函数式编程以 Java8ish 风格的方式解决问题 - 还不能使用 Java 8 本身...... :)

标签: java functional-programming guava apache-commons functor


【解决方案1】:

Olivier Grégoirecommented正确答案:

使用 Guava,您需要一个简单的 Multiset,更具体地说是它的 EnumMultiset 实现。 Multiset 是一种用于跟踪计数元素的数据结构。

给定您的List&lt;TypeEnum&gt; types,您可以使用create 创建一个EnumMultiset

Multiset<TypeEnum> multiset = EnumMultiset.create(types);

您可以使用count 查询Multiset 中元素的计数:

multiset.count(TypeEnum.A); // 2
multiset.count(TypeEnum.B); // 1

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多