Creating a list with repeating element

后端 未结 5 535
一生所求
一生所求 2020-12-29 01:00

Is there an utility method in Java that generates a list or array of a specified length with all elements equal to a specified value (e.g [\"foo\", \"foo\", \"foo\", \"foo\"

5条回答
  •  长情又很酷
    2020-12-29 01:33

    If your object are not immutable or not reference-transparent, you can use

    Stream.generate(YourClass::new).limit()
    

    and collect it to list

    .collect(Collectors.toList())
    

    or to array

    .toArray(YourClass[]::new)
    

提交回复
热议问题