Home > Mobile >  Is this how I initialize a list with values in Kotlin?
Is this how I initialize a list with values in Kotlin?

Time:07-13

I want to store a number of counts per value, something like this:

value count
0  -> 6
1  -> 2
2  -> 0
3  -> 7

As shown in the example, the values start at 0 and are consecutive integers.

I want to initialize all counts with 0, so that I can then increment them.

This is what I came up with:

val histogram = Array(numBuckets) { 0 }.toMutableList() as ArrayList
histogram[2]  

It works, but the initialization feels a bit convoluted. Is there a better way? Is the ArrayList the correct collection for the job in the place?

CodePudding user response:

You can just use the MutableList constructor:

val histogram = MutableList(numBuckets) { 0 }

CodePudding user response:

Kevin Coppock's answer works well if the values in the value-count pairs are consecutive and starting at 0. Then the array or list index stands for the value in the value-count pair.

If more flexibility is needed, for example if the values

  • do not start at zero,
  • have a step which is not 1,
  • or have irregular steps (e.g. logarithmic),

it might make sense to introduce pairs, either as Pair<Int, Int> or in the form of a data class:

import kotlin.math.pow

data class HistogramEntry(
  var value: Int,
  var count: Int
)

Example:

val numBuckets = 5

val regularHistogram = List(numBuckets) { HistogramEntry(it, 0) }

regularHistogram[2].count  

regularHistogram(::println)

Output:

HistogramEntry(value=0, count=0)
HistogramEntry(value=1, count=0)
HistogramEntry(value=2, count=1)
HistogramEntry(value=3, count=0)
HistogramEntry(value=4, count=0)

Another example:

val numBuckets = 5

val logarithmicHistogram = List(numBuckets) { HistogramEntry(10f.pow(it   1).toInt(), 0) }

logarithmicHistogram[2].count = 12345

logarithmicHistogram.forEach(::println)

Output:

HistogramEntry(value=10, count=0)
HistogramEntry(value=100, count=0)
HistogramEntry(value=1000, count=12345)
HistogramEntry(value=10000, count=0)
HistogramEntry(value=100000, count=0)

And of course a HistogramEntry list could also be built manually:

val list = listOf(
  HistogramEntry(value = 234, count = 0),
  HistogramEntry(value = 36, count = 0),
  HistogramEntry(value = 9, count = 0),
  HistogramEntry(value = 178, count = 0),
  HistogramEntry(value = 11, count = 0)
)
  • Related