Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Create an ArrayList of random Integers of specified length?

Tags:

java

kotlin

I have an ArrayList like this :

var amplititudes : ArrayList<Int> = ArrayList()

I want to populate this with random Ints. How can I do this?

like image 819
Dishonered Avatar asked May 29 '18 09:05

Dishonered


People also ask

How do I get the size of an arrayList in Kotlin?

To get size of Array in Kotlin, read the size property of this Array object. size property returns number of elements in this Array. We can also use count() function of the Array class to get the size.


1 Answers

One option is to use the array constructor as following:

var amplititudes  = IntArray(10) { Random().nextInt() }.asList()

Another strategy is:

var amplititudes  = (1..10).map { Random().nextInt() }

EDIT

As suggested in the comment instead of creating an instance of Random each time it is better to initialize it once:

var ran = Random()
var amplititudes  = (1..10).map { ran.nextInt() }
like image 142
Md Johirul Islam Avatar answered Oct 16 '22 02:10

Md Johirul Islam