Mar*_*Lux 2 java collections loops
如何在不使用任何循环的情况下修改集合中的值以获取具有修改值的新集合?
例如,我有一个Collection<String>并且想要用括号括起所有字符串.
有了循环,我会这样做:
Iterable<String> collection = getCollection();
ArrayList<String> newCollection = new ArrayList<String>();
for(String str : collection)
newCollection.add("(" + str + ")");
Run Code Online (Sandbox Code Playgroud)
必须有一个更优雅的解决方案.
编辑:允许使用第三方实用程序:)
不,没有.仅使用JDK类,您无法做得更好. 检查我的第二个答案
编辑
试试谷歌收藏库Lists.trasform:
List<String> out = Lists.transform(in, new Function<String, String>() {
public String apply(String s) {
return String.format("(%s)", s);
}
});
Run Code Online (Sandbox Code Playgroud)