Skip to content
Advertisement

Java List Stream

I am attempting to simplify my code but list stream is not working. I am creating an instance of a class (that contains an inner class) in a static method and trying to take items from the first list and instantiate them in the inner class and add them to a new list. My code works with fruit loops if that matters, I just want to get rid of excess loops. Below is a copy of what I tried.

JavaScript

I am trying to do this multiple times (at least two so far) so simply setting a new ArrayList instance to this won’t work for me. I know I can simply do this with a single loop but I am trying to learn how to use list streams as it has other methods that I find particularly useful and this is the first problem I have run into so far, and I cannot find examples online on this.

Apologies in advance for my poor formatting, this is my first post.

edit(Solved): in the constructor for outerclass, I redeclared the type ArrayList for secondArrayList and that is why it was not working.

Advertisement

Answer

To add all results of your stream to your secondArrayList you could just

JavaScript

Or alternatively, without intermediate list, adding elements one by one

JavaScript

Full example (demonstrating both versions):

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement