Idiomatic way to generate a random alphanumeric string in Kotlin





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







18















I can generate a random sequence of numbers in a certain range like the following:



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()
}


Then I'll have to extend List with:



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


Then I can do:



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("")
}


But maybe there's a better way?










share|improve this question































    18















    I can generate a random sequence of numbers in a certain range like the following:



    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()
    }


    Then I'll have to extend List with:



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


    Then I can do:



    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("")
    }


    But maybe there's a better way?










    share|improve this question



























      18












      18








      18


      4






      I can generate a random sequence of numbers in a certain range like the following:



      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()
      }


      Then I'll have to extend List with:



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


      Then I can do:



      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("")
      }


      But maybe there's a better way?










      share|improve this question
















      I can generate a random sequence of numbers in a certain range like the following:



      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()
      }


      Then I'll have to extend List with:



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


      Then I can do:



      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("")
      }


      But maybe there's a better way?







      kotlin






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 26 '17 at 1:53







      breezymri

















      asked Oct 26 '17 at 0:07









      breezymribreezymri

      86721633




      86721633
























          10 Answers
          10






          active

          oldest

          votes


















          22














          Assuming you have a specific set of source characters (source in this snippet), you could do this:



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


          Which gives strings like "LYANFGNPNI" for outputStrLength = 10.



          The two important bits are





          1. Random().ints(length, minValue, maxValue) which produces a stream of length random numbers each from minValue to maxValue-1, and


          2. asSequence() which converts the not-massively-useful IntStream into a much-more-useful Sequence<Int>.






          share|improve this answer





















          • 2





            As a Kotlin newby I was look for this solution - very cool! However I would use source.length instead of source.length - 1, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.

            – ToBe
            Nov 16 '17 at 10:10






          • 2





            Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...

            – Paul Hicks
            Nov 16 '17 at 20:47











          • Fixed now, in example and description.

            – Paul Hicks
            Nov 16 '17 at 20:49






          • 1





            I get an unresolved reference on the .asSequence() as IntStream doesn't have that method

            – z3ntu
            Mar 7 '18 at 13:59






          • 1





            @PaulHicks you can use .toArray() instead of .asSequence() without the need to import additional methods.

            – denys
            Jan 9 at 12:44



















          16














          Lazy folks would just do



          java.util.UUID.randomUUID().toString()


          You can not restrict the character range here, but I guess it's fine in many situations anyway.






          share|improve this answer

































            8














            Without JDK8:



            fun ClosedRange<Char>.randomString(lenght: Int) = 
            (1..lenght)
            .map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
            .joinToString("")


            usage:



            ('a'..'z').randomString(6)





            share|improve this answer

































              4














              Since Kotlin 1.3 you can do this:



              fun getRandomString(length: Int) : String {
              val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
              return (1..length)
              .map { allowedChars.random() }
              .joinToString("")
              }





              share|improve this answer































                2














                Or use coroutine API for the true Kotlin spirit:



                buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
                .take(10)
                .map{(it+ 65).toChar()}
                .joinToString("")





                share|improve this answer



















                • 1





                  The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them. (1..10).forEach { yield(r.nextInt(24) + 65).toChar() }

                  – Marko Topolnik
                  May 29 '18 at 10:29





















                1














                ('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")





                share|improve this answer



















                • 1





                  While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review

                  – Nick
                  Nov 24 '18 at 6:50



















                1














                Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...) also wasn't working for me, as it required an API level of 24 on Android to use it.



                This is how I'm doing it with Kotlin's Random abstract class:



                import kotlin.random.Random

                object IdHelper {

                private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
                private const val LENGTH = 20

                fun generateId(): String {
                return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
                .map { ALPHA_NUMERIC[it] }
                .joinToString(separator = "")
                }
                }


                The process and how this works is similar to a lot of the other answers already posted here:




                1. Generate a list of numbers of length LENGTH that correspond to the index values of the source string, which in this case is ALPHA_NUMERIC

                2. Map those numbers to the source string, converting each numeric index to the character value

                3. Convert the resulting list of characters to a string, joining them with the empty string as the separator character.

                4. Return the resulting string.


                Usage is easy, just call it like a static function: IdHelper.generateId()






                share|improve this answer

































                  1














                  Using Kotlin 1.3:



                  This method uses an input of your desired string length desiredStrLength as an Integer and returns a random alphanumeric String of your desired string length.



                  fun randomAlphaNumericString(desiredStrLength: Int): String {
                  val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')

                  return (1..desiredStrLength)
                  .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                  .map(charPool::get)
                  .joinToString("")
                  }


                  If you prefer unknown length of alphanumeric (or at least a decently long string length like 36 in my example below), this method can be used:



                  fun randomAlphanumericString(): String {
                  val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                  val outputStrLength = (1..36).shuffled().first()

                  return (1..outputStrLength)
                  .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                  .map(charPool::get)
                  .joinToString("")
                  }





                  share|improve this answer































                    1














                    fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
                    val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                    return alphaNumeric.shuffled().take(lenght).joinToString("")
                    }





                    share|improve this answer
























                    • While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!

                      – d_kennetz
                      Feb 19 at 18:00





















                    0














                    The best way I think:



                    fun generateID(size: Int): String {
                    val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
                    return (source).map { it }.shuffled().subList(0, size).joinToString("")
                    }





                    share|improve this answer
























                    • But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?

                      – Tobias Reich
                      Jan 3 at 9:10












                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    autoActivateHeartbeat: false,
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f46943860%2fidiomatic-way-to-generate-a-random-alphanumeric-string-in-kotlin%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    10 Answers
                    10






                    active

                    oldest

                    votes








                    10 Answers
                    10






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    22














                    Assuming you have a specific set of source characters (source in this snippet), you could do this:



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


                    Which gives strings like "LYANFGNPNI" for outputStrLength = 10.



                    The two important bits are





                    1. Random().ints(length, minValue, maxValue) which produces a stream of length random numbers each from minValue to maxValue-1, and


                    2. asSequence() which converts the not-massively-useful IntStream into a much-more-useful Sequence<Int>.






                    share|improve this answer





















                    • 2





                      As a Kotlin newby I was look for this solution - very cool! However I would use source.length instead of source.length - 1, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.

                      – ToBe
                      Nov 16 '17 at 10:10






                    • 2





                      Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...

                      – Paul Hicks
                      Nov 16 '17 at 20:47











                    • Fixed now, in example and description.

                      – Paul Hicks
                      Nov 16 '17 at 20:49






                    • 1





                      I get an unresolved reference on the .asSequence() as IntStream doesn't have that method

                      – z3ntu
                      Mar 7 '18 at 13:59






                    • 1





                      @PaulHicks you can use .toArray() instead of .asSequence() without the need to import additional methods.

                      – denys
                      Jan 9 at 12:44
















                    22














                    Assuming you have a specific set of source characters (source in this snippet), you could do this:



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


                    Which gives strings like "LYANFGNPNI" for outputStrLength = 10.



                    The two important bits are





                    1. Random().ints(length, minValue, maxValue) which produces a stream of length random numbers each from minValue to maxValue-1, and


                    2. asSequence() which converts the not-massively-useful IntStream into a much-more-useful Sequence<Int>.






                    share|improve this answer





















                    • 2





                      As a Kotlin newby I was look for this solution - very cool! However I would use source.length instead of source.length - 1, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.

                      – ToBe
                      Nov 16 '17 at 10:10






                    • 2





                      Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...

                      – Paul Hicks
                      Nov 16 '17 at 20:47











                    • Fixed now, in example and description.

                      – Paul Hicks
                      Nov 16 '17 at 20:49






                    • 1





                      I get an unresolved reference on the .asSequence() as IntStream doesn't have that method

                      – z3ntu
                      Mar 7 '18 at 13:59






                    • 1





                      @PaulHicks you can use .toArray() instead of .asSequence() without the need to import additional methods.

                      – denys
                      Jan 9 at 12:44














                    22












                    22








                    22







                    Assuming you have a specific set of source characters (source in this snippet), you could do this:



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


                    Which gives strings like "LYANFGNPNI" for outputStrLength = 10.



                    The two important bits are





                    1. Random().ints(length, minValue, maxValue) which produces a stream of length random numbers each from minValue to maxValue-1, and


                    2. asSequence() which converts the not-massively-useful IntStream into a much-more-useful Sequence<Int>.






                    share|improve this answer















                    Assuming you have a specific set of source characters (source in this snippet), you could do this:



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


                    Which gives strings like "LYANFGNPNI" for outputStrLength = 10.



                    The two important bits are





                    1. Random().ints(length, minValue, maxValue) which produces a stream of length random numbers each from minValue to maxValue-1, and


                    2. asSequence() which converts the not-massively-useful IntStream into a much-more-useful Sequence<Int>.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 19 at 22:59

























                    answered Oct 26 '17 at 1:07









                    Paul HicksPaul Hicks

                    9,65832856




                    9,65832856








                    • 2





                      As a Kotlin newby I was look for this solution - very cool! However I would use source.length instead of source.length - 1, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.

                      – ToBe
                      Nov 16 '17 at 10:10






                    • 2





                      Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...

                      – Paul Hicks
                      Nov 16 '17 at 20:47











                    • Fixed now, in example and description.

                      – Paul Hicks
                      Nov 16 '17 at 20:49






                    • 1





                      I get an unresolved reference on the .asSequence() as IntStream doesn't have that method

                      – z3ntu
                      Mar 7 '18 at 13:59






                    • 1





                      @PaulHicks you can use .toArray() instead of .asSequence() without the need to import additional methods.

                      – denys
                      Jan 9 at 12:44














                    • 2





                      As a Kotlin newby I was look for this solution - very cool! However I would use source.length instead of source.length - 1, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.

                      – ToBe
                      Nov 16 '17 at 10:10






                    • 2





                      Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...

                      – Paul Hicks
                      Nov 16 '17 at 20:47











                    • Fixed now, in example and description.

                      – Paul Hicks
                      Nov 16 '17 at 20:49






                    • 1





                      I get an unresolved reference on the .asSequence() as IntStream doesn't have that method

                      – z3ntu
                      Mar 7 '18 at 13:59






                    • 1





                      @PaulHicks you can use .toArray() instead of .asSequence() without the need to import additional methods.

                      – denys
                      Jan 9 at 12:44








                    2




                    2





                    As a Kotlin newby I was look for this solution - very cool! However I would use source.length instead of source.length - 1, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.

                    – ToBe
                    Nov 16 '17 at 10:10





                    As a Kotlin newby I was look for this solution - very cool! However I would use source.length instead of source.length - 1, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.

                    – ToBe
                    Nov 16 '17 at 10:10




                    2




                    2





                    Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...

                    – Paul Hicks
                    Nov 16 '17 at 20:47





                    Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...

                    – Paul Hicks
                    Nov 16 '17 at 20:47













                    Fixed now, in example and description.

                    – Paul Hicks
                    Nov 16 '17 at 20:49





                    Fixed now, in example and description.

                    – Paul Hicks
                    Nov 16 '17 at 20:49




                    1




                    1





                    I get an unresolved reference on the .asSequence() as IntStream doesn't have that method

                    – z3ntu
                    Mar 7 '18 at 13:59





                    I get an unresolved reference on the .asSequence() as IntStream doesn't have that method

                    – z3ntu
                    Mar 7 '18 at 13:59




                    1




                    1





                    @PaulHicks you can use .toArray() instead of .asSequence() without the need to import additional methods.

                    – denys
                    Jan 9 at 12:44





                    @PaulHicks you can use .toArray() instead of .asSequence() without the need to import additional methods.

                    – denys
                    Jan 9 at 12:44













                    16














                    Lazy folks would just do



                    java.util.UUID.randomUUID().toString()


                    You can not restrict the character range here, but I guess it's fine in many situations anyway.






                    share|improve this answer






























                      16














                      Lazy folks would just do



                      java.util.UUID.randomUUID().toString()


                      You can not restrict the character range here, but I guess it's fine in many situations anyway.






                      share|improve this answer




























                        16












                        16








                        16







                        Lazy folks would just do



                        java.util.UUID.randomUUID().toString()


                        You can not restrict the character range here, but I guess it's fine in many situations anyway.






                        share|improve this answer















                        Lazy folks would just do



                        java.util.UUID.randomUUID().toString()


                        You can not restrict the character range here, but I guess it's fine in many situations anyway.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Mar 16 '18 at 8:14

























                        answered Mar 16 '18 at 7:53









                        Holger BrandlHolger Brandl

                        4,3373229




                        4,3373229























                            8














                            Without JDK8:



                            fun ClosedRange<Char>.randomString(lenght: Int) = 
                            (1..lenght)
                            .map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
                            .joinToString("")


                            usage:



                            ('a'..'z').randomString(6)





                            share|improve this answer






























                              8














                              Without JDK8:



                              fun ClosedRange<Char>.randomString(lenght: Int) = 
                              (1..lenght)
                              .map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
                              .joinToString("")


                              usage:



                              ('a'..'z').randomString(6)





                              share|improve this answer




























                                8












                                8








                                8







                                Without JDK8:



                                fun ClosedRange<Char>.randomString(lenght: Int) = 
                                (1..lenght)
                                .map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
                                .joinToString("")


                                usage:



                                ('a'..'z').randomString(6)





                                share|improve this answer















                                Without JDK8:



                                fun ClosedRange<Char>.randomString(lenght: Int) = 
                                (1..lenght)
                                .map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
                                .joinToString("")


                                usage:



                                ('a'..'z').randomString(6)






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Mar 7 '18 at 21:58

























                                answered Mar 7 '18 at 21:01









                                Andrzej SawoniewiczAndrzej Sawoniewicz

                                398613




                                398613























                                    4














                                    Since Kotlin 1.3 you can do this:



                                    fun getRandomString(length: Int) : String {
                                    val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
                                    return (1..length)
                                    .map { allowedChars.random() }
                                    .joinToString("")
                                    }





                                    share|improve this answer




























                                      4














                                      Since Kotlin 1.3 you can do this:



                                      fun getRandomString(length: Int) : String {
                                      val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
                                      return (1..length)
                                      .map { allowedChars.random() }
                                      .joinToString("")
                                      }





                                      share|improve this answer


























                                        4












                                        4








                                        4







                                        Since Kotlin 1.3 you can do this:



                                        fun getRandomString(length: Int) : String {
                                        val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
                                        return (1..length)
                                        .map { allowedChars.random() }
                                        .joinToString("")
                                        }





                                        share|improve this answer













                                        Since Kotlin 1.3 you can do this:



                                        fun getRandomString(length: Int) : String {
                                        val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
                                        return (1..length)
                                        .map { allowedChars.random() }
                                        .joinToString("")
                                        }






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jan 28 at 11:24









                                        WhiteAngelWhiteAngel

                                        680421




                                        680421























                                            2














                                            Or use coroutine API for the true Kotlin spirit:



                                            buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
                                            .take(10)
                                            .map{(it+ 65).toChar()}
                                            .joinToString("")





                                            share|improve this answer



















                                            • 1





                                              The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them. (1..10).forEach { yield(r.nextInt(24) + 65).toChar() }

                                              – Marko Topolnik
                                              May 29 '18 at 10:29


















                                            2














                                            Or use coroutine API for the true Kotlin spirit:



                                            buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
                                            .take(10)
                                            .map{(it+ 65).toChar()}
                                            .joinToString("")





                                            share|improve this answer



















                                            • 1





                                              The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them. (1..10).forEach { yield(r.nextInt(24) + 65).toChar() }

                                              – Marko Topolnik
                                              May 29 '18 at 10:29
















                                            2












                                            2








                                            2







                                            Or use coroutine API for the true Kotlin spirit:



                                            buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
                                            .take(10)
                                            .map{(it+ 65).toChar()}
                                            .joinToString("")





                                            share|improve this answer













                                            Or use coroutine API for the true Kotlin spirit:



                                            buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
                                            .take(10)
                                            .map{(it+ 65).toChar()}
                                            .joinToString("")






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Mar 16 '18 at 8:14









                                            Holger BrandlHolger Brandl

                                            4,3373229




                                            4,3373229








                                            • 1





                                              The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them. (1..10).forEach { yield(r.nextInt(24) + 65).toChar() }

                                              – Marko Topolnik
                                              May 29 '18 at 10:29
















                                            • 1





                                              The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them. (1..10).forEach { yield(r.nextInt(24) + 65).toChar() }

                                              – Marko Topolnik
                                              May 29 '18 at 10:29










                                            1




                                            1





                                            The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them. (1..10).forEach { yield(r.nextInt(24) + 65).toChar() }

                                            – Marko Topolnik
                                            May 29 '18 at 10:29







                                            The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them. (1..10).forEach { yield(r.nextInt(24) + 65).toChar() }

                                            – Marko Topolnik
                                            May 29 '18 at 10:29













                                            1














                                            ('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")





                                            share|improve this answer



















                                            • 1





                                              While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review

                                              – Nick
                                              Nov 24 '18 at 6:50
















                                            1














                                            ('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")





                                            share|improve this answer



















                                            • 1





                                              While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review

                                              – Nick
                                              Nov 24 '18 at 6:50














                                            1












                                            1








                                            1







                                            ('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")





                                            share|improve this answer













                                            ('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Nov 23 '18 at 16:12









                                            Louis SaglioLouis Saglio

                                            39447




                                            39447








                                            • 1





                                              While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review

                                              – Nick
                                              Nov 24 '18 at 6:50














                                            • 1





                                              While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review

                                              – Nick
                                              Nov 24 '18 at 6:50








                                            1




                                            1





                                            While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review

                                            – Nick
                                            Nov 24 '18 at 6:50





                                            While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review

                                            – Nick
                                            Nov 24 '18 at 6:50











                                            1














                                            Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...) also wasn't working for me, as it required an API level of 24 on Android to use it.



                                            This is how I'm doing it with Kotlin's Random abstract class:



                                            import kotlin.random.Random

                                            object IdHelper {

                                            private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
                                            private const val LENGTH = 20

                                            fun generateId(): String {
                                            return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
                                            .map { ALPHA_NUMERIC[it] }
                                            .joinToString(separator = "")
                                            }
                                            }


                                            The process and how this works is similar to a lot of the other answers already posted here:




                                            1. Generate a list of numbers of length LENGTH that correspond to the index values of the source string, which in this case is ALPHA_NUMERIC

                                            2. Map those numbers to the source string, converting each numeric index to the character value

                                            3. Convert the resulting list of characters to a string, joining them with the empty string as the separator character.

                                            4. Return the resulting string.


                                            Usage is easy, just call it like a static function: IdHelper.generateId()






                                            share|improve this answer






























                                              1














                                              Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...) also wasn't working for me, as it required an API level of 24 on Android to use it.



                                              This is how I'm doing it with Kotlin's Random abstract class:



                                              import kotlin.random.Random

                                              object IdHelper {

                                              private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
                                              private const val LENGTH = 20

                                              fun generateId(): String {
                                              return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
                                              .map { ALPHA_NUMERIC[it] }
                                              .joinToString(separator = "")
                                              }
                                              }


                                              The process and how this works is similar to a lot of the other answers already posted here:




                                              1. Generate a list of numbers of length LENGTH that correspond to the index values of the source string, which in this case is ALPHA_NUMERIC

                                              2. Map those numbers to the source string, converting each numeric index to the character value

                                              3. Convert the resulting list of characters to a string, joining them with the empty string as the separator character.

                                              4. Return the resulting string.


                                              Usage is easy, just call it like a static function: IdHelper.generateId()






                                              share|improve this answer




























                                                1












                                                1








                                                1







                                                Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...) also wasn't working for me, as it required an API level of 24 on Android to use it.



                                                This is how I'm doing it with Kotlin's Random abstract class:



                                                import kotlin.random.Random

                                                object IdHelper {

                                                private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
                                                private const val LENGTH = 20

                                                fun generateId(): String {
                                                return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
                                                .map { ALPHA_NUMERIC[it] }
                                                .joinToString(separator = "")
                                                }
                                                }


                                                The process and how this works is similar to a lot of the other answers already posted here:




                                                1. Generate a list of numbers of length LENGTH that correspond to the index values of the source string, which in this case is ALPHA_NUMERIC

                                                2. Map those numbers to the source string, converting each numeric index to the character value

                                                3. Convert the resulting list of characters to a string, joining them with the empty string as the separator character.

                                                4. Return the resulting string.


                                                Usage is easy, just call it like a static function: IdHelper.generateId()






                                                share|improve this answer















                                                Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...) also wasn't working for me, as it required an API level of 24 on Android to use it.



                                                This is how I'm doing it with Kotlin's Random abstract class:



                                                import kotlin.random.Random

                                                object IdHelper {

                                                private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
                                                private const val LENGTH = 20

                                                fun generateId(): String {
                                                return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
                                                .map { ALPHA_NUMERIC[it] }
                                                .joinToString(separator = "")
                                                }
                                                }


                                                The process and how this works is similar to a lot of the other answers already posted here:




                                                1. Generate a list of numbers of length LENGTH that correspond to the index values of the source string, which in this case is ALPHA_NUMERIC

                                                2. Map those numbers to the source string, converting each numeric index to the character value

                                                3. Convert the resulting list of characters to a string, joining them with the empty string as the separator character.

                                                4. Return the resulting string.


                                                Usage is easy, just call it like a static function: IdHelper.generateId()







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Dec 16 '18 at 14:40

























                                                answered Dec 15 '18 at 23:16









                                                Kyle FalconerKyle Falconer

                                                5,25423256




                                                5,25423256























                                                    1














                                                    Using Kotlin 1.3:



                                                    This method uses an input of your desired string length desiredStrLength as an Integer and returns a random alphanumeric String of your desired string length.



                                                    fun randomAlphaNumericString(desiredStrLength: Int): String {
                                                    val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')

                                                    return (1..desiredStrLength)
                                                    .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                                                    .map(charPool::get)
                                                    .joinToString("")
                                                    }


                                                    If you prefer unknown length of alphanumeric (or at least a decently long string length like 36 in my example below), this method can be used:



                                                    fun randomAlphanumericString(): String {
                                                    val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                                                    val outputStrLength = (1..36).shuffled().first()

                                                    return (1..outputStrLength)
                                                    .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                                                    .map(charPool::get)
                                                    .joinToString("")
                                                    }





                                                    share|improve this answer




























                                                      1














                                                      Using Kotlin 1.3:



                                                      This method uses an input of your desired string length desiredStrLength as an Integer and returns a random alphanumeric String of your desired string length.



                                                      fun randomAlphaNumericString(desiredStrLength: Int): String {
                                                      val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')

                                                      return (1..desiredStrLength)
                                                      .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                                                      .map(charPool::get)
                                                      .joinToString("")
                                                      }


                                                      If you prefer unknown length of alphanumeric (or at least a decently long string length like 36 in my example below), this method can be used:



                                                      fun randomAlphanumericString(): String {
                                                      val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                                                      val outputStrLength = (1..36).shuffled().first()

                                                      return (1..outputStrLength)
                                                      .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                                                      .map(charPool::get)
                                                      .joinToString("")
                                                      }





                                                      share|improve this answer


























                                                        1












                                                        1








                                                        1







                                                        Using Kotlin 1.3:



                                                        This method uses an input of your desired string length desiredStrLength as an Integer and returns a random alphanumeric String of your desired string length.



                                                        fun randomAlphaNumericString(desiredStrLength: Int): String {
                                                        val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')

                                                        return (1..desiredStrLength)
                                                        .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                                                        .map(charPool::get)
                                                        .joinToString("")
                                                        }


                                                        If you prefer unknown length of alphanumeric (or at least a decently long string length like 36 in my example below), this method can be used:



                                                        fun randomAlphanumericString(): String {
                                                        val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                                                        val outputStrLength = (1..36).shuffled().first()

                                                        return (1..outputStrLength)
                                                        .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                                                        .map(charPool::get)
                                                        .joinToString("")
                                                        }





                                                        share|improve this answer













                                                        Using Kotlin 1.3:



                                                        This method uses an input of your desired string length desiredStrLength as an Integer and returns a random alphanumeric String of your desired string length.



                                                        fun randomAlphaNumericString(desiredStrLength: Int): String {
                                                        val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')

                                                        return (1..desiredStrLength)
                                                        .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                                                        .map(charPool::get)
                                                        .joinToString("")
                                                        }


                                                        If you prefer unknown length of alphanumeric (or at least a decently long string length like 36 in my example below), this method can be used:



                                                        fun randomAlphanumericString(): String {
                                                        val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                                                        val outputStrLength = (1..36).shuffled().first()

                                                        return (1..outputStrLength)
                                                        .map{ kotlin.random.Random.nextInt(0, charPool.size) }
                                                        .map(charPool::get)
                                                        .joinToString("")
                                                        }






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Jan 16 at 21:17









                                                        jojojojo

                                                        8401328




                                                        8401328























                                                            1














                                                            fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
                                                            val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                                                            return alphaNumeric.shuffled().take(lenght).joinToString("")
                                                            }





                                                            share|improve this answer
























                                                            • While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!

                                                              – d_kennetz
                                                              Feb 19 at 18:00


















                                                            1














                                                            fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
                                                            val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                                                            return alphaNumeric.shuffled().take(lenght).joinToString("")
                                                            }





                                                            share|improve this answer
























                                                            • While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!

                                                              – d_kennetz
                                                              Feb 19 at 18:00
















                                                            1












                                                            1








                                                            1







                                                            fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
                                                            val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                                                            return alphaNumeric.shuffled().take(lenght).joinToString("")
                                                            }





                                                            share|improve this answer













                                                            fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
                                                            val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
                                                            return alphaNumeric.shuffled().take(lenght).joinToString("")
                                                            }






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Feb 19 at 13:43









                                                            Sefa GürelSefa Gürel

                                                            111




                                                            111













                                                            • While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!

                                                              – d_kennetz
                                                              Feb 19 at 18:00





















                                                            • While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!

                                                              – d_kennetz
                                                              Feb 19 at 18:00



















                                                            While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!

                                                            – d_kennetz
                                                            Feb 19 at 18:00







                                                            While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!

                                                            – d_kennetz
                                                            Feb 19 at 18:00













                                                            0














                                                            The best way I think:



                                                            fun generateID(size: Int): String {
                                                            val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
                                                            return (source).map { it }.shuffled().subList(0, size).joinToString("")
                                                            }





                                                            share|improve this answer
























                                                            • But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?

                                                              – Tobias Reich
                                                              Jan 3 at 9:10
















                                                            0














                                                            The best way I think:



                                                            fun generateID(size: Int): String {
                                                            val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
                                                            return (source).map { it }.shuffled().subList(0, size).joinToString("")
                                                            }





                                                            share|improve this answer
























                                                            • But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?

                                                              – Tobias Reich
                                                              Jan 3 at 9:10














                                                            0












                                                            0








                                                            0







                                                            The best way I think:



                                                            fun generateID(size: Int): String {
                                                            val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
                                                            return (source).map { it }.shuffled().subList(0, size).joinToString("")
                                                            }





                                                            share|improve this answer













                                                            The best way I think:



                                                            fun generateID(size: Int): String {
                                                            val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
                                                            return (source).map { it }.shuffled().subList(0, size).joinToString("")
                                                            }






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Nov 29 '18 at 21:30









                                                            Mickael BelhassenMickael Belhassen

                                                            26011




                                                            26011













                                                            • But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?

                                                              – Tobias Reich
                                                              Jan 3 at 9:10



















                                                            • But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?

                                                              – Tobias Reich
                                                              Jan 3 at 9:10

















                                                            But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?

                                                            – Tobias Reich
                                                            Jan 3 at 9:10





                                                            But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?

                                                            – Tobias Reich
                                                            Jan 3 at 9:10


















                                                            draft saved

                                                            draft discarded




















































                                                            Thanks for contributing an answer to Stack Overflow!


                                                            • Please be sure to answer the question. Provide details and share your research!

                                                            But avoid



                                                            • Asking for help, clarification, or responding to other answers.

                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                            To learn more, see our tips on writing great answers.




                                                            draft saved


                                                            draft discarded














                                                            StackExchange.ready(
                                                            function () {
                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f46943860%2fidiomatic-way-to-generate-a-random-alphanumeric-string-in-kotlin%23new-answer', 'question_page');
                                                            }
                                                            );

                                                            Post as a guest















                                                            Required, but never shown





















































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown

































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown







                                                            這個網誌中的熱門文章

                                                            Tangent Lines Diagram Along Smooth Curve

                                                            Yusuf al-Mu'taman ibn Hud

                                                            Zucchini