java - 在多个转换之间共享值?

标签 java design-patterns guava

假设我有以下值列表:

List<String> values = Lists.asList("a", "a", "b", "c");

现在我想为所有值添加一个索引,以便最终将其作为列表:

a1 a2 b1 c1 // imagine numbers as subscript

我想使用FluentIterable及其 transform方法,所以像这样:

from(values).transform(addIndexFunction);

问题在于,addIndexFunction 需要知道索引增加的频率 - 想想 a2,在将索引添加到此 时a,该函数需要知道已经有一个a1

那么,是否有某种最佳实践来做这样的事情?我当前的想法是创建一个以每个字母作为键的 Map,所以:

Map<String,Integer> counters = new HashMap<>();
// the following should be generated automatically, but for the sake of this example it's done manually...
counters.put("a", 0);
counters.put("b", 0);
counters.put("c", 0);

然后修改我的转换调用:

from(values).transform(addIndexFunction(counters));

由于 Map 是一个对象并通过引用传递,所以我现在可以在转换之间共享计数器状态,对吧?反馈,更好的想法? Guava 中是否有一些内置的机制来处理此类事情?

感谢您的任何提示!

最佳答案

使用Multiset来替换 HashMap,您就可以按照 @Perception 的建议将 Multiset 封装在 Function 本身中,并在应用函数时聚合数据。

关于java - 在多个转换之间共享值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15747906/

相关文章:

java - Guava 中有 Empty 吗?

java - 在 Guava 中链接 Future 时处理异常

java - 如何将通配符泛型与 Sets.powerSet 一起使用

Java 8、流过滤器、反射、NoSuchMethodException

php - 计费系统最佳实践

java - 强制事务回滚而不遇到异常?

design-patterns - 是否可以在 Haskell 中为排序二叉树创建 Functor 实例?

ios - AppDelegate 文件在哪里适合 MVC?

Java服务器帮助!

java - 执行所有 Eclipse 建议标记