在Java7中,能否使用函子/函数式编程对列表进行分组(并对每组中的元素进行计数)?

在Java7中,能否使用函子/函数式编程对列表进行分组(并对每组中的元素进行计数)?,java,functional-programming,guava,apache-commons,functor,Java,Functional Programming,Guava,Apache Commons,Functor,你能分组List types=newarraylist(Arrays.asList(TypeEnum.A,TypeEnum.B,TypeEnum.A))转换为映射计数类型,使用functor(例如)preJava8 我试图了解函数式编程,但不确定这类事情是否真的可行(因为我不仅仅是映射集合值,而是尝试聚合) 在命令式风格中,我会这样做: public Map<TypeEnum, Integer> countByGroup(List<TypeEnum> types) {

你能分组
List types=newarraylist(Arrays.asList(TypeEnum.A,TypeEnum.B,TypeEnum.A))转换为
映射计数类型,使用functor(例如)preJava8

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

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

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;
}
公共地图countByGroup(列表类型){
Map countedTypes=新HashMap();
for(类型枚举类型:类型){
if(计数类型.容器(类型)){
countedTypes.put(type,countedTypes.get(type)+1);
}否则{
countedTypes.put(类型1);
}
}
返回计数类型;
}

编辑:依赖副作用似乎有点不合适——或者就是这样做的

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
过程计数=新过程(){
公共映射countPerType=null;
@凌驾
公共无效运行(类型枚举类型){
if(countPerType.containsKey(类型)){
countPerType.put(type,countPerType.get(type)+1);
}否则{
countPerType.put(类型1);
}
}
公共过程初始化(映射计数类型){
this.countPerType=countPerType;
归还这个;
}
}.init(countPerType);//荣誉http://stackoverflow.com/a/12206542/2018047
正确答案:


使用番石榴,您需要一个简单的、更具体的实现
Multiset
是一种用于跟踪已计数元素的数据结构

给定您的
列表类型
,您可以使用以下方法创建
枚举多集


使用番石榴,您需要一个简单的、更具体的实现
Multiset
是一种用于跟踪已计数元素的数据结构。Java 8不是魔术,即流API由使用接口类型参数的普通Java代码组成。没有理由不在Java8之前的环境中工作。是的,我知道。正如我所说的,我正试图通过使用函数式编程以Java8ish风格的方式解决问题,而不必使用Java8本身…:)
Multiset<TypeEnum> multiset = EnumMultiset.create(types);
multiset.count(TypeEnum.A); // 2
multiset.count(TypeEnum.B); // 1