从现有集合创建新集合

时间:2014-08-18 22:24:01

标签: java guava

我有一组对象如下:

Collection<Foo>

其中Foo

public class Foo {

    private User user;
    private Item item;

    public Foo(User user, Item item) {
        this.user = user;
        this.item = item;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Item getItem() {
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }

}

我想使用Collection<Item>返回另一个Collection<Foo>类型的集合。我可以通过使用for loop并循环收集,获取项目并将其添加到新列表来实现此目的。到目前为止,我已使用Google Guava使用谓词创建Collection<Foo>

Google番石榴中是否有方法/功能允许我从Collection<Item>创建Collection<Foo>?我应该使用转换功能吗?

1 个答案:

答案 0 :(得分:4)

如果您可以使用Java 8:

Collection<Item> items = foos.stream()
            .map(Foo::getItem)
            .collect(toList());

否则你确实可以use the transform method。在你的情况下:

Function<Foo, Item> f = 
    new Function<Foo, Item>() { 
        public Item apply(Foo foo) { return foo.getItem(); }
    };

Collection<Item> items = Collections2.transform(foos, f);