Dóra Takács wrote:. . . "Mama Gorilla" would be added once only, because sets must stay unique?
You do not appear to have any sets in the code you wrote. Unless you use something like
.distinct()
in line 6½, you are dealing with a Stream<List<Animal>> and the Mama Gorilla would appear twice because it is in two Lists. If however you use something like
.collect(Collectors.toSet())
then you will create a Set and Mama Gorilla will only appear once.
If you don't flatten your forEach call will print
[]
[Bonobo, Mama Gorilla]
[Mama Gorilla, Baby Gorilla]
… because you have the three Lists. If you flatten the Streams you will get
Bonobo
Mama Gorilla
Mama Gorilla
Baby Gorilla
… and converting it to a set will give
{Bonobo, Mama Gorilla, Baby Gorilla}
I suggest you put a peek call somewhere in your code.
animals.peek(l -> System.out.println(l))
animals.flatMap(...).peek(l -> System.out.println(l))
Remember you will get no output until you write something “downstream” of that to make the Streams run and “consume” their inputs.
Another suggestion: run the code on Eclipse. Hover your mouse over each method call, and a tooltip will appear with the type of the expression in. It will read something like Stream<Animal> or Stream<List<Animal>>, and you can follow the different types of Stream through the execution.
Style thing: Separate your Stream code so each method call is on its own line and the . operators line up vertically. It will make hovering the mouse on Eclipse easier, too.
You will have to think of an argument to pass to my flatMap calls. List::stream or Arrays::stream as Urma Fusco and Mycroft suggested might work.