我有一个关于使用Google Collections(更新: Guava)简化一些集合处理代码的问题。
我有一堆“Computer”对象,并且我想最终得到它们的“资源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(而且目前无法更改),但在这种情况下,我希望从生成的字符串集合中省略 null。
以下是过滤 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);
}
}
使用上述方法肯定也是一种选择,但出于好奇心(和想学习更多谷歌集合的愿望),你能否使用谷歌集合以更短或更优雅的方式做完全相同的事情?