如何将 List<A> 转换为 List<B>?
How can I transform a List<A> into List<B>?
如果 A 是这样定义的:
class A {
List<B> bList;
}
如果给定 A 的列表 (List aList),我如何将其转换为包含存储在 aList 的每个元素中的所有 B 的列表?
我想用番石榴来做这个。
这应该可以。
ImmutableList<B> listOfBs = FluentIterable.from(listOfAs)
.transformAndConcat(new Function<A, List<B>>(){
public List<B> apply(A a) {
return a.bList;
}
})
.toList();
Java 8 解
我知道你想要一个 Guava 解决方案,但这里有一个 Java 8 版本供任何感兴趣的人使用。
为每个 A
项创建映射 A.bList
的流以馈入映射函数。
List<B> bList = aList.stream().map(a -> a.bList).flatMap(b -> b.stream()).collect(Collectors.toList());
备注
这里有一个类似 flatMap
的例子:Java 8 flatMap Example。
此外,您可以查看:
如果 A 是这样定义的:
class A {
List<B> bList;
}
如果给定 A 的列表 (List aList),我如何将其转换为包含存储在 aList 的每个元素中的所有 B 的列表? 我想用番石榴来做这个。
这应该可以。
ImmutableList<B> listOfBs = FluentIterable.from(listOfAs)
.transformAndConcat(new Function<A, List<B>>(){
public List<B> apply(A a) {
return a.bList;
}
})
.toList();
Java 8 解
我知道你想要一个 Guava 解决方案,但这里有一个 Java 8 版本供任何感兴趣的人使用。
为每个 A
项创建映射 A.bList
的流以馈入映射函数。
List<B> bList = aList.stream().map(a -> a.bList).flatMap(b -> b.stream()).collect(Collectors.toList());
备注
这里有一个类似 flatMap
的例子:Java 8 flatMap Example。
此外,您可以查看: