您能使用函子(例如,List<TypeEnum> types = new ArrayList(Arrays.asList(TypeEnum.A, TypeEnum.B, TypeEnum.A));,Apache公域函子)将pre Java 8组合成一个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发布于 2017-01-09 16:13:34
https://stackoverflow.com/questions/41514257
复制相似问题