How to pick every time new or unique random item from a array list in android?


I need to pick a new item from a list that hasn’t been picked already until there are no more.

Here is my code:

private var quizQuestionList: ArrayList<Quiz> 
private var pickedItems: ArrayList<Int>
private var random: Random  Random()

private fun pickItem(): Quiz {
    var index  random?.nextInt(quizQuestionList!!.size)

    if (pickedItems.contains(index)) {
        index  random?.nextInt(quizQuestionList!!.size)
    } else {

    val item  quizQuestionList!!.get(index!!)
    return item

Please suggest any solution that gives me a new item every time. I used an int list for all previously picked items and check every time when picked new item but I didn’t get success.


It isn’t obvious what you are looking for, but it looks like you want to show different Quiz question from ArrayList. In condition of, when that question is shown, no more same question will be shown. Here is how you should do, I will give you just the logic you could try it yourself:

import java.util.Random

fun main(args: Array<String>) {

    val random  Random()
    var randomInt: Int
    var pickedInt: MutableSet<Int>  mutableSetOf()

    fun rand(from: Int, to: Int): Int{
            randomInt  random.nextInt(to - from) + from

        return randomInt

    while(pickedInt.size < 9){
        var differentNumber  rand(1,11)

This will print nine different Number. The way I choosing MutableSet is because it will only have unique values, no duplicated value. Hope it helps!

Answered By – willy wijaya

Leave a Comment