从List中随机取N个不重复数据

2022-10-31  本文已影响0人  努力2009

获取N个随机数,还是很容易出现重复,需要注意去重

2022-10-14 21:38:16.408 6746-6786 D getRandomList: index=132
2022-10-14 21:38:16.408 6746-6786 D getRandomList: index=93
2022-10-14 21:38:16.408 6746-6786 D getRandomList: index=92
2022-10-14 21:38:16.408 6746-6786 D getRandomList: index=92
2022-10-14 21:38:16.408 6746-6786 D getRandomList: index=121

private fun getRandomList(rawList: List<String>, needListSize: Int): List<String> {
    return if (rawList.isNotEmpty()) {
        if (needListSize > 0) {
            val counts = if (needListSize > rawList.size) rawList.size else needListSize
            val randomSet = mutableSetOf<String>()
            for (index in rawList.indices) {
                if (randomSet.size == counts) {
                    break
                }
                val randomIndex = (rawList.indices).random()
                LogUtils.d(LOG_TAG, "getRandomList: index=", randomIndex)
                randomSet.add(rawList[randomIndex])
            }
            randomSet.toList()
        } else {
            rawList
        }
    } else {
        emptyList()
    }
}
上一篇 下一篇

猜你喜欢

热点阅读