Kotlin - creating a mutable list with repeating elements

ListKotlin

List Problem Overview


What would be an idiomatic way to create a mutable list of a given length n with repeating elements of value v (e.g listOf(4,4,4,4,4)) as an expression.

I'm doing val list = listOf((0..n-1)).flatten().map{v} but it can only create an immutable list.

List Solutions


Solution 1 - List

Use:

val list = MutableList(n) {index -> v}

or, since index is unused, you could omit it:

val list = MutableList(n) { v }

Solution 2 - List

another way may be:

val list = generateSequence { v }.take(4).toMutableList()

This style is compatible with both MutableList and (Read Only) List

Solution 3 - List

If you want different objects you can use repeat. For example,

 val list = mutableListOf<String>().apply {
   repeat(2){ this.add(element = "YourObject($it)") }
 }

Replace String with your object. Replace 2 with number of elements you want.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBasel ShishaniView Question on Stackoverflow
Solution 1 - ListvoddanView Answer on Stackoverflow
Solution 2 - ListAlpha HoView Answer on Stackoverflow
Solution 3 - ListShivanand DarurView Answer on Stackoverflow