【发布时间】:2010-12-20 15:10:16
【问题描述】:
我有一个关于在使用 Google Collections 时简化一些 Collection 处理代码的问题(更新:Guava)。
我有一堆“计算机”对象,我想以它们的“资源 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 收藏集),您能否使用 Google 收藏集以更短或更优雅的方式做同样的事情?
【问题讨论】:
标签: java collections refactoring guava