I have a question about the use of the collect method of the Stream class. For learning I have created a stream with some Person objects, and I try to convert this stream to a List using the difficult way (not using a predefined collector). So I have create the following code first:
This works fine so, to make this code a bit smaller, I rewrote it as follows:
To me this looks functionally the same as the first block of code but the compiler complains about the collect, add and addAll methods. So, I rewrote this sample to explicitly tell the compiler the type of the variables of the lambda's:
Unfortunately, this code also doesn't compile. The compiler still complains about the type of the two BiConsumer arguments. To me it seems that it must be possible to implement the collector this way. Could someone explain what is wrong with this code?
Rob Spoor gave me the clue I was looking for; I forgot the () -> in the line where I create the supplier....
About using the complicated way to create a collector: I am studying for OCP, and I try to get used to use the functional interfaces. So, the creation of the collector myself was just an exercise and has no practical goal.