Java 用番石榴从一个变为多个
在这种情况下,我需要将多个源对象中的多个值提取到一个集合中。我试图通过番石榴的转换来实现这一点,但遇到了一个问题,我得到了一个集合,我必须手动“展平”。有没有一种很好的方法可以直接在平面集合中获取结果Java 用番石榴从一个变为多个,java,collections,transform,guava,Java,Collections,Transform,Guava,在这种情况下,我需要将多个源对象中的多个值提取到一个集合中。我试图通过番石榴的转换来实现这一点,但遇到了一个问题,我得到了一个集合,我必须手动“展平”。有没有一种很好的方法可以直接在平面集合中获取结果 private static final Function<Target, Collection<Integer>> EXTRACT_FUNCTION = new Function<SourceObject, Collection<Integer>>
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);
private静态最终函数EXTRACT\u Function=new Function(){
@凌驾
公共集合应用(SourceObject o){
//从o中提取并返回整数集合
返回列表。newArrayList(…);
}
};
集合sourceObjects=。。。
Collection>nestedResults=transform(sourceObjects,EXTRACT_函数);
//现在,我必须通过在nestedResults上循环并执行addAll来手动展平结果。。
//这能避免吗?
收集结果=平坦嵌套结果(嵌套结果);
您可以使用番石榴的Iterables.concat(Iterable…coll)对一些Iterable结果进行分组您要求的是一种减少
/折叠
方法。目前,Guava
不支持它,尽管存在一个未决问题:
最好不要使用
函数
,而是迭代它并添加到一个集合中。番石榴是一个很好的框架,但它不能做任何事情。我不知道Iterables.concat(Iterable…coll)
,如果你不介意结果是Iterable
而不是Collection
,你可以使用它。还有一个类似的问题:如果你真的需要一个集合,你通常可以组合Iterables.concat()
使用复制方法,例如Lists.newArrayList()
,ImmutableList.copyOf()
,set.newHashSet()
,或ImmutableSet.copyOf()
。返回Iterable视图是非常聪明的,因为它允许您选择结果集合类型,而不是为您任意选择一种。如果您不需要真正的集合,它还可以避免复制元素。这是正确的。Iterables.concat将替代FlatteNestedResults函数。