I have a List of custom Foo objects each containing 2 lists of Cat and Dog objects as seen below:
class Foo { List<Cat> cats; List<Dog> dogs; } class Cat { int id; } class Dog { String name; } I have a method where I pass in a List request and I would like to flatten that to a single Foo object containing each requests dogs and cats flattened together. Is there a clean compact way to do so?
Source List:
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); Result should be:
Foo with a List = catsForOne + catsForTwo and a List = dogsForTwo
This is a toy example but you can imagine that foo has about 5-6 collections (ie. Cat, Dog, Pig, Duck etc.) and I would like to have a compact solution with Java 8. The naive one that I can do is to loop over the requests and keep adding all the collections one by one to a final result Foo.
Assume Foo, Cat, Dog etc. are from an external library and thus their source code cannot be altered.
List<Object> list = new ArrayList<>(); for (Foo foo : fooList) { list.addAll(foo.cats); list.addAll(foo.dogs); }Lists flattened. If that's not what you meant, then clarify the question.Fooobjects?