我有定製的Foo對象貓和犬的各自含有2名列表的列表的對象的對象列表,如下所示:合併含列表
class Foo {
List<Cat> cats;
List<Dog> dogs;
}
class Cat {
int id;
}
class Dog {
String name;
}
我有一種方法,其中我通過在一個列表請求和我想將它平化爲一個Foo對象,其中包含每個請求狗和貓放在一起。有沒有一個乾淨的緊湊的方式來做到這一點?
源列表:
List<Cat> catsForOne = new ArrayList<>(); // add a bunch of cats
List<Cat> catsForTwo = new ArrayList<>(); // add a bunch of cats
List<Dog> dogsForTwo = new ArrayList<>(); // add a bunch of dogs
List<Foo> requests = new ArrayList<>();
Foo one = Foo.builder().cats(catsForOne).build();
Foo two = Foo.builder().dogs(dogsForTwo).cats(catsForTwo).build();
requests.add(one);
requests.add(two);
的結果應該是:
美孚用List = catsForOne + catsForTwo和List = dogsForTwo
這是一個玩具的例子,但你可以想象FOO有約5-6個集合(即Cat,Dog,Pig,Duck等),我想用Java 8構建一個緊湊的解決方案。我可以做的一個天真的工作是循環請求並不斷添加所有一一收集到最終結果Foo。
假設Foo,Cat,Dog等來自外部庫,因此它們的源代碼不能改變。
您能否提供請求來源清單的定義? – eg04lt3r
'List
編輯了這個問題,希望它更清楚! –