【发布时间】:2017-05-21 17:18:39
【问题描述】:
您能否使用仿函数(例如 Google's Guava、Apache's Commons Functor)pre 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