[英]Share values between several transformations?
想象一下,我具有以下值列表:
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是一个对象并通过引用传递,所以我现在可以在转换之间共享计数器状态,对吗? 反馈,更好的主意? 番石榴中是否有一些内置的机制来处理这些事情?
感谢您的提示!
使用Multiset代替HashMap,按照@Perception的建议将Multiset封装在Function本身中,并在应用该函数时聚合数据,您就可以开始了。
不要在此处使用transform
,否则每次迭代时,您的可迭代项将具有不同的值,并且通常表现得很怪异。 (在Function
具有状态也有些皱眉。)
而是使用Multiset
辅助程序进行适当的for
循环:
Multiset<String> counts = HashMultiset.create();
List<Subscript> result = Lists.newArrayList();
for (String value : values) {
int count = counts.add(value, 1);
result.add(new Subscript(value, count));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.