在Kotlin中生成一个随机字母数字字符串的习惯方法

我可以在一定范围内产生随机数字序列,如下所示:

fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start fun generateRandomNumberList(len: Int, low: Int = 0, high: Int = 255): List<Int> { (0..len-1).map { (low..high).random() }.toList() } 

那么我将不得不扩展List

 fun List<Char>.random() = this[Random().nextInt(this.size)] 

那我可以这样做:

 fun generateRandomString(len: Int = 15): String{ val alphanumerics = CharArray(26) { it -> (it + 97).toChar() }.toSet() .union(CharArray(9) { it -> (it + 48).toChar() }.toSet()) return (0..len-1).map { alphanumerics.toList().random() }.joinToString("") } 

但也许有更好的办法?

假设你有一组特定的源字符( source代码片段),你可以这样做:

 val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" Random().ints(outputStrLength, 0, source.length -1) .asSequence() .map(source::get) .joinToString("") 

这给了outputStrLength = 10的“LYANFGNPNI”这样的字符串。

两个重要的位是

  1. Random().ints(length, minValue, maxValue) ,它产生一个从minValuemaxValue长度随机数字流,
  2. asSequence()将不大量使用的IntStream转换成更有用的Sequence<Int>