假设我有以下值列表:
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/