在 C# 中我可以这样做:
IEnumerable<long> ids = things.select(x => x.Id);
在 Java 中我必须这样做:
Collection<Long> ids = new ArrayList<Long>(things.size());
for(Thing x : things)
ids.add(x.getId());
现在必须经常做这类事情,想知道是否有更通用的方法在 Java 中执行此操作。可以创建一个方法来执行此操作,但随后我将不得不添加一个带有 getId 方法或类似方法的接口(interface)...我不能...
最佳答案
使用 Guava ,特别是 function interface :
public class ThingFunction implements Function<Thing, Long> {
@Override
public Long apply(Thing thing) {
return user.getId();
}
}
并像这样调用(其中 transform 是从 guava 的 Collections2 静态导入的:
Collection<Long> ids = transform(things, new ThingFunction());
Guava 有不少other benefits也是。
关于java - 收集集合中对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8210382/