Collect property of objects in collection
In C# I can do this:
IEnumerable<long> ids = things.select(x => x.Id);
In Java I have to do this:
Collection<Long> ids = new ArrayList<Long>(things.size());
for(Thing x : things)
ids.add(x.getId());
Have to do this sort of thing quite a lot now and wonder if there is a more generic way to do this in Java. Could create a method to do it, but then I would have to add an interface with the getId method or something like that... which I can't...
using Guava, specifically the function interface :
public class ThingFunction implements Function<Thing, Long> {
@Override
public Long apply(Thing thing) {
return user.getId();
}
}
and invoked like this (where transform is a static import from Collections2 of guava:
Collection<Long> ids = transform(things, new ThingFunction());
Guava has quite a few other benefits too.
使用Apache Commons的BeanUtils和Collections:
Collection<Long> ids = CollectionUtils.collect(things,
new BeanToPropertyValueTransformer("id"));
In Groovy
you would only have to do this:
Set ids = things.collect{ aThing -> aThing.Id}
That would give you all the Ids
from all the things in Things
as a list.
Here is some info on Groovy, and some differences compared to Java
链接地址: http://www.djcxy.com/p/10068.html上一篇: 如何导入/包含在封闭样式表中?
下一篇: 收集集合中的对象的属性