使用 Guava 从一到多的转变

发布于 12-19 22:46 字数 834 浏览 2 评论 0原文

我有这样的情况:我想从多个源对象中提取多个值到一个集合中。我尝试通过 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);

I have situation where I want to extract multiple values from multiple source objects into a collection. I tried to achieve this with Guava's transform, but ran into the problem that I get back a collection of collections which I have to 'flatten' manually. Is there a nice way to get the results back directly in a flat collection?

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

横笛休吹塞上声2024-12-26 22:46:54

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

You can use Guava's Iterables.concat(Iterable<E>... coll) to group few iterable results

鯉魚旗2024-12-26 22:46:54

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

也许最好不要使用函数,但是迭代它并添加到一个集合中。 Guava 是一个很棒的框架,但它并不能解决所有问题。

What you are asking is a reduce / fold method. Currently Guava does not support it though there is an open issue: http://code.google.com/p/guava-libraries/issues/detail?id=218

Maybe it's a better idea that you do not use a Function, but iterate it and add to one collection. Guava is a great framework but it cannot do everything.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文