[英]how to transform object list with list attribute to one list with all list attribute itemes contained
我有一個像這樣的對象:
class House {
String name;
List<Door> doors;
}
我想要做的是將List<House>
轉換為包含所有houses
所有doors
的List<Door>
。
有沒有機會用番石榴做這個?
我嘗試使用guava使用Lists.transform函數,但我只得到一個List<List<Door>>
作為結果。
如果您確實需要使用函數方法,可以使用FluentIterable#transformAndConcat執行此操作:
public static ImmutableList<Door> foo(List<House> houses) {
return FluentIterable
.from(houses)
.transformAndConcat(GetDoorsFunction.INSTANCE)
.toImmutableList();
}
private enum GetDoorsFunction implements Function<House, List<Door>> {
INSTANCE;
@Override
public List<Door> apply(House input) {
return input.getDoors();
}
}
FluentIterable.from(listOfHouses).transformAndConcat(doorFunction)
會做得很好。
你不需要番石榴(假設我理解正確):
final List<Door> doorsFromAllHouses = Lists.newArrayList();
for (final House house : houses) {
doorsFromAllHouses.addAll(house.doors);
}
// and doorsFromAllHouses is full of all kinds of doors from various houses
使用Lists.transform
作為list of houses
輸入list of houses
和轉換功能get all doors from a house
都給你正確輸出list of *each house's doors*
(這正是List<List<Door>>
) List<List<Door>>
。
更一般地說,你需要使用reduce
/ fold
函數而不是transform,這在Guava中沒有實現( 參見本期 ),主要是因為Java的詳細語法和for-each循環的存在就足夠了。 您將能夠減少Java 8(或者您現在可以使用任何其他主流語言執行此操作......)。 偽Java8代碼:
List<Door> doors = reduce(
houses, // collection to reduce from
new ArrayList<Door>(), // initial accumulator value
house, acc -> acc.addAll(house.doors)); // reducing function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.