Search code examples
kotlinarraylistinitialization

How do I add multiple copies of the same String to an existing ArrayList?


I have an ArrayList<String>. I want to add n copies of a new String to it.

I've Googled generally and searched on StackOverflow. I've looked at the documentation.

Surely there's a better way than doing a loop?

I was hoping for something like:

myArray.addAll (ArrayList<String>(count: 10, value: "123"))

Solution

  • You can initialize a List with a given size n and an initializer function like this:

    fun main() {
        val n = 10
        val defaultList = List(n) { it -> "default" }  // you can leave "it ->" here
        println(defaultList)
    }
    

    This piece of code then outputs

    [default, default, default, default, default, default, default, default, default, default]
    

    If you want to intialize an Array<String> directly without using a List as intermediate, you can do

    val defaultArray: Array<String> = Array(n) { "default" }
    println(defaultArray.contentToString())
    

    in the main and get the same output (even without the it ->, which, indeed, isn't necessary in this case).