gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:13:10 25 4
gpt4 key购买 nike

假设我有以下值列表:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com