java – 收集集合中对象的属性

前端之家收集整理的这篇文章主要介绍了java – 收集集合中对象的属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在C#中,我可以这样做:
IEnumerable<long> ids = things.select(x => x.Id);@H_502_3@ 
 

在Java中我必须这样做:

Collection<Long> ids = new ArrayList<Long>(things.size());
for(Thing x : things)
   ids.add(x.getId());@H_502_3@ 
 

现在必须做很多这样的事情并且想知道在Java中是否有更通用的方法来做这件事.可以创建一个方法来做到这一点,但后来我将不得不添加一个getId方法的接口或类似的…我不能…

解决方法

使用 Guava,特别是 function interface
public class ThingFunction implements Function<Thing,Long> {
    @Override
    public Long apply(Thing thing) {
        return user.getId();
    }
}@H_502_3@ 
 

并且像这样调用(其中transform是来自guava的Collections2的静态导入:

Collection<Long> ids = transform(things,new ThingFunction());@H_502_3@ 
 

番石榴也有相当多的other benefits.

原文链接:https://www.f2er.com/java/128522.html

猜你在找的Java相关文章