在使用 Google Collections(更新:Guava)时,我有一个关于简化一些 Collection 处理代码的问题。
我有一堆“计算机”对象,我想最终得到他们的“资源 ID”的集合。这样做是这样的:
Collection<Computer> matchingComputers = findComputers();
Collection<String> resourceIds =
Lists.newArrayList(Iterables.transform(matchingComputers, new Function<Computer, String>() {
public String apply(Computer from) {
return from.getResourceId();
}
}));
现在,getResourceId()
可能会返回 null(并且现在无法更改它),但在这种情况下,我想从结果 String 集合中省略 null。
这是过滤空值的一种方法:
Collections2.filter(resourceIds, new Predicate<String>() {
@Override
public boolean apply(String input) {
return input != null;
}
});
你可以像这样把所有这些放在一起:
Collection<String> resourceIds = Collections2.filter(
Lists.newArrayList(Iterables.transform(matchingComputers, new Function<Computer, String>() {
public String apply(Computer from) {
return from.getResourceId();
}
})), new Predicate<String>() {
@Override
public boolean apply(String input) {
return input != null;
}
});
但这对于如此简单的任务来说并不优雅,更不用说可读了!事实上,普通的旧 Java 代码(根本没有花哨的 Predicate 或 Function 的东西)可以说会更干净:
Collection<String> resourceIds = Lists.newArrayList();
for (Computer computer : matchingComputers) {
String resourceId = computer.getResourceId();
if (resourceId != null) {
resourceIds.add(resourceId);
}
}
使用上述方法当然也是一种选择,但出于好奇(以及想了解更多 Google Collections 的愿望),您可以使用 Google Collections 以更短或更优雅的方式做同样的事情吗?