使用 Guava 从一到多的转变
我有这样的情况:我想从多个源对象中提取多个值到一个集合中。我尝试通过 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 技术交流群。

发布评论
评论(2)
鯉魚旗2024-12-26 22:46:54
您要求的是一个 reduce
/ fold
方法。目前,Guava
不支持它,但存在一个未解决的问题:http://code.google.com/p/guava-libraries/issues/detail?id=218
也许最好不要使用函数
,但是迭代它并添加到一个集合中。 Guava 是一个很棒的框架,但它并不能解决所有问题。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您可以使用 Guava 的
Iterables.concat(Iterable... coll)
对几个可迭代结果进行分组You can use Guava's
Iterables.concat(Iterable<E>... coll)
to group few iterable results