【问题标题】:Creating a new collection from an existing collection从现有集合创建新集合
【发布时间】:2014-10-11 22:30:21
【问题描述】:

我有一个对象集合如下:

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&lt;Foo&gt; 返回另一个Collection&lt;Item&gt; 类型的集合。我可以通过使用for loop 并遍历Collection、获取项目并将其添加到新列表来做到这一点。到目前为止,我已经使用 Google Guava 使用谓词创建了我的 Collection&lt;Foo&gt;

Google guava 中是否有一种方法/功能可以让我从Collection&lt;Foo&gt; 创建一个Collection&lt;Item&gt;?我应该使用转换功能吗?

【问题讨论】:

    标签: java guava


    【解决方案1】:

    如果你可以使用 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);
    

    【讨论】:

    • 如果不能选择 Java 8,您能否提供一个替代解决方案?
    • 请注意,如果您使用transform,则结果是原始集合的实时视图。这与使用 Java 8 方法或循环不同,因为它们都返回一个新集合,当您更改原始集合时该集合不会改变。如果需要,您可以随时将该视图复制到新集合中。
    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2011-04-16
    • 1970-01-01
    • 2018-09-20
    • 2021-08-04
    相关资源
    最近更新 更多