Skip to content Skip to sidebar Skip to footer

Getting Random Values From An ArrayList

I have a String array: String [] array={'1','2','3','4','5','6','7','8','9'}; Which I convert into an array list: ArrayList al = new ArrayList(Arrays.

Solution 1:

Use Random class to do that, argument of method nextInt is the bound on the random number to be returned. It must be positive:

Random random = new Random();
yourList.get(random.nextInt(yourList.size()));

Solution 2:

Simple Kotlin Solution

myList.random()

random() is a default extension function included in base Kotlin on the Collection object.

Documentation


Post a Comment for "Getting Random Values From An ArrayList"