例如我有一个列表,我想对它们调用一个函数并列出返回的答案
final List<String> sources = new ArrayList<>();
// initialize
final List<Integer> answers = new ArrayList<>();
for(final String source : sources)
answers.add(calculate(source));
GoogleGuava
或 ApacheCommons
中有没有什么标准函数可以使用它来代替这些乱七八糟的代码
喜欢(示例目的):
final List<String> answers = Lists.calculate(sources, new CalculateListener(..));
为了便于理解:UnderscoreJs
在 JavaScript 中有一个方法 map
我想要在 java GoogleGuava
或 ApacheCommons
如果存在
最佳答案
你可以玩一下 Function
接口(interface)和 Iterables
类。
从您的示例中我可以看出,您正在尝试将源转换为计算源,因此代码看起来喜欢:
Function<String, String> transformer = new Function<String, String>() {
public String apply(String source) {
return calculate(source);
}
};
Iterable<String> calculatedSources = Iterables.transform(sources, transformer);
List<String> calculatedSourcesAsAList = Lists.newArrayList(calculatedSources);
作为旁注,这种常见的操作类型在 Java8 的 Stream 功能中得到了很好的涵盖,您只需将源映射到计算的源,然后收集结果。而且它只是一行:
sources.stream().map(source -> calculate(source)).collect(Collectors.toList());
关于Java Lists 列表项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31202521/