【问题标题】:Transforming from one to many with Guava使用番石榴从一转变为多
【发布时间】:2012-01-15 17:33:14
【问题描述】:

我有一种情况,我想从多个源对象中提取多个值到一个集合中。我试图通过 Guava 的转换来实现这一点,但遇到了一个问题,即我取回了必须手动“展平”的集合集合。有没有一种很好的方法可以将结果直接返回到平面集合中?

private static final Function<Target, Collection<Integer>> EXTRACT_FUNCTION = new Function<SourceObject, Collection<Integer>>() {
    @Override
    public Collection<Integer> apply(SourceObject o) {
        // extract and return a collection of integers from o
        return Lists.newArrayList(..);
    }
};

Collection<SourceObject> sourceObjects = ...
Collection<Collection<Integer>>> nestedResults = transform(sourceObjects, EXTRACT_FUNCTION);

// Now I have to manually flatten the results by looping and doing addAll over the nestedResults.. 
// Can this be avoided?
Collection<Integer> results = flattenNestedResults(nestedResults);

【问题讨论】:

    标签: java collections transform guava


    【解决方案1】:

    您要问的是reduce / fold 方法。目前Guava 不支持它,但有一个未解决的问题:http://code.google.com/p/guava-libraries/issues/detail?id=218

    也许最好不要使用Function,而是迭代它并添加到一个集合中。 Guava 是一个很棒的框架,但它不能无所不能。

    【讨论】:

    • 我不知道Iterables.concat(Iterable&lt;E&gt;... coll),如果您不介意结果是Iterable 而不是Collection,可以使用它
    • 如果确实需要收藏,一般可以将Iterables.concat()Lists.newArrayList()ImmutableList.copyOf()Sets.newHashSet()ImmutableSet.copyOf()等复制方式结合使用。返回一个 Iterable 视图非常聪明,因为它允许您选择结果集合类型,而不是为您任意选择一个。如果您不需要真正的集合,它还可以避免复制元素。
    【解决方案2】:

    您可以使用 Guava 的 Iterables.concat(Iterable&lt;E&gt;... coll) 对几个可迭代的结果进行分组

    【讨论】:

    • 这是正确的。 Iterables.concat 将替代您的 flattenNestedResults 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多