合并包含列表的对象列表

Joh*_*aum 2 java java-8

我有一个自定义Foo对象列表,每个对象包含2个Cat和Dog对象列表,如下所示:

class Foo {
   List<Cat> cats;
   List<Dog> dogs;
}

class Cat {
   int id;
}

class Dog {
   String name;
}
Run Code Online (Sandbox Code Playgroud)

我有一个方法,我传入一个List请求,我想把它压平到一个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);
Run Code Online (Sandbox Code Playgroud)

结果应该是:

Foo有一个List = catsForOne + catsForTwo和一个List = dogsForTwo

这是一个玩具示例,但你可以想象foo有大约5-6个集合(即Cat,Dog,Pig,Duck等),我想拥有一个Java 8的紧凑解决方案.我可以做的天真的是循环请求并继续将所有集合逐个添加到最终结果Foo.

假设Foo,Cat,Dog等来自外部库,因此其源代码无法更改.

Sch*_*uca 5

您可以单独收集它们,然后创建一个新Foo对象并分配lists给它.

 List<Dog> collectDogs = foos.stream().flatMap(foo -> foo.getCats().stream())
                       .collect(Collectors.toList());
 List<Cat> collectCats = foos.stream().flatMap(foo -> foo.getDogs().stream())
                      .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

然后

Foo result = new Foo();
result.setDogs(collectDogs);
result.setCats(collectCats);
Run Code Online (Sandbox Code Playgroud)

  • 加上一个简单和阅读这样的代码也很容易 (2认同)