2012-12-18 48 views

回答

0

你不需要番石榴它(假設我理解正確的你):

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和轉換功能get all doors from a house給你的list of *each house's doors*正確的輸出(這正是List<List<Door>>)。

更一般地,你想要reduce/fold function而不是在Guava(see this issue)中實現的轉換,主要是因爲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 
6
FluentIterable.from(listOfHouses).transformAndConcat(doorFunction) 

會做的工作就好了。

7

如果你確實需要使用的功能的方法,你可以使用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(); 
    } 
}