Creating a list with repeating element

后端 未结 5 531
一生所求
一生所求 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:32

    Version you can use for primitive arrays(Java 8):

    DoubleStream.generate(() -> 123.42).limit(777).toArray(); // returns array of 777 123.42 double vals
    

    Note that it returns double[], not Double[]

    Works for IntegerStream, DoubleStream, LongStream

    UPD

    and for string dups you can use:

    Stream.generate(() -> "value").limit(400).toArray()

    No extra libs required, single line

提交回复
热议问题