[英]Java Lists list item values
I have a List for example and I want to call a function on them and list returned answers 我有一个List例子,我想调用它们的函数并列出返回的答案
final List<String> sources = new ArrayList<>();
// initialize
final List<Integer> answers = new ArrayList<>();
for(final String source : sources)
answers.add(calculate(source));
Is there any standard function in GoogleGuava
or ApacheCommons
to use it instead of these messy codes GoogleGuava
或ApacheCommons
是否有任何标准功能可以使用它而不是这些凌乱的代码
Like (example purpose): 喜欢(示例目的):
final List<String> answers = Lists.calculate(sources, new CalculateListener(..));
And for easy understanding: UnderscoreJs
in JavaScript has a method map
I want something like that in java GoogleGuava
or ApacheCommons
if exists 为了便于理解:JavaScript中的
UnderscoreJs
有一个方法map
我想在java GoogleGuava
或ApacheCommons
存在类似的东西,如果存在的话
You can play a bit with the Function
interface and the Iterables
class. 您可以使用
Function
接口和Iterables
类进行一些操作。
From what I can see from your example, you're trying to transform a source to calculated source , so the code would look like: 从我的示例中可以看出,您正在尝试将 源 转换为计算源 ,因此代码如下所示:
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);
As a side note, this often seen type of operation is very well covered in the Java8's Stream features, where you would have to just map the sources to the calculated ones and then collect the result. 作为旁注,Java8的Stream功能非常清楚地介绍了这种常见的操作类型,您必须将源映射到计算的源,然后收集结果。 And it's just a one-liner:
它只是一个单行:
sources.stream().map(source -> calculate(source)).collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.