Search code examples
javaarraylistmultidimensional-arrayinitialization

How to initialise 2d ArrayList with streams


I have 2D ArrayList like this one: ArrayList<ArrayList<SingleCell>> grid;. I want to initialize it like in this example with normal ArrayList:

List<Person> persons = Stream.generate(Person::new)
                             .limit(60)
                             .collect(Collectors.toList());

I’m getting width and height when constructing the holder class. I want to fill the 2D ArrayList with new SingleCell(); based on the passed size. Is it possible to do it like this and if it is possible how can i do it ? Also is there any better way?


Solution

  • In the example you give, Person::new is used to generate the elements of a list, but this generator could be any lambda you like, so how about something like this:

    List<List<SingleCell>> grid =
        Stream.generate(()->
            Stream.generate(SingleCell::new)
            .limit(width)
            .collect(Collectors.toList())
        )
        .limit(height)
        .collect(Collectors.toList());