- Generate a Random Alphanumeric String in Kotlin
- 2. Dependencies
- 3. Java Random
- 4. Kotlin Random
- 5. Apache Common Lang
- 6. Performance
- 7. Conclusion
- Saved searches
- Use saved searches to filter your results more quickly
- License
- lamba92/KRandomStrings
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Создать случайную буквенно-цифровую строку в Kotlin
- 2. Зависимости
- 3. Java Random
- 4. Kotlin Random
- 5. Общий язык Apache
- 6. Производительность
- 7. Заключение
- Популярные посты
Generate a Random Alphanumeric String in Kotlin
In this tutorial, we’ll discuss how to generate a random alphanumeric String in Kotlin using three different approaches: Java Random, Kotlin Random, and Apache Commons Lang RandomStringUtils.
Then, we’ll wrap up with a look at a high-performance approach.
2. Dependencies
Before we dive into the tutorial, let’s add the Apache Commons Lang dependency into our pom.xml:
org.apache.commons commons-lang3 3.8.1
In addition, we can set up some constants for later reference:
const val STRING_LENGTH = 10; const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+";
3. Java Random
First of all, let’s look at how to use Java Random to generate a random String.
In this example, we’ll use ThreadLocalRandom which has a Random instance per thread and safeguards against contention:
private val charPool : List = (‘a’..’z’) + (‘A’..’Z’) + (‘0’..’9′) @Test fun givenAStringLength_whenUsingJava_thenReturnAlphanumericString()
In this example, we’re getting 10 random alphanumeric characters from character pool by generating their indexes, then join them together to create the random String.
ThreadLocalRandom is available since JDK 7. We could use java.util.Random instead. But if multiple threads use the same instance of Random, the same seed is shared by multiple threads, causing thread contention.
However, neither ThreadLocalRandom nor Random are cryptographically secure, as it’s possible to guess the next value returned from the generator. Java does provide the noticeably slower java.security.SecureRandom to securely generate a random value.
4. Kotlin Random
From Kotlin 1.3, kotlin.random.Random is available as a multiplatform feature. It uses java.util.Random in JDK 6 and 7, ThreadLocalRandom in JDK 8+ and Math.random in Javascript.
We can get a random String with the same approach:
val randomString = (1..STRING_LENGTH) .map < i ->kotlin.random.Random.nextInt(0, charPool.size) > .map(charPool::get) .joinToString("");
5. Apache Common Lang
Finally, if we’re still using Kotlin, we can make use of Apache Common Lang libraries to generate a random String:
@Test fun givenAStringLength_whenUsingApacheCommon_thenReturnAlphanumericString()
In this example, we simply call RandomStringUtils.randomAlphanumeric to get our String with a predefined length.
We should note that RandomStringUtils generate random values by using java.util.Random, which isn’t cryptographically secure as we discussed above. So in case of generating a secured token or value, we can use CryptoRandom in Apache Commons Crypto or Java’s SecureRandom.
We have a tutorial about how to generate a random String in Java as well to cover this topic in more details.
6. Performance
A notable aspect of each of these is that it is calling our random number generator STRING_LENGTH times. If we are creating many Strings or long Strings, these approaches may be too slow. With some extra effort, though, we can simply call for a random sequence of bytes, and then map them to our char pool:
@Test fun givenAStringLength_whenUsingRandomForBytes_thenReturnAlphanumericString() < val random = SecureRandom() val bytes = ByteArray(STRING_LENGTH) random.nextBytes(bytes) val randomString = (0..bytes.size - 1) .map < i ->charPool.get((bytes[i] and 0xFF.toByte() and (charPool.size-1).toByte()).toInt()) >.joinToString("") assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) assertEquals(STRING_LENGTH, randomString.length) >
What makes this approach powerful is that, while we still do STRING_LENGTH lookups to our charPool, we only call on our random generator once. And, aside from being faster, this may also reduce thread contention on shared instances.
Also, note that while bytes[i] and 0xFF.toByte() and charPool.size.toByte() may look advanced, it’s just a way to make sure the random bytes are between 0 and charPool.size().
7. Conclusion
In conclusion, we’ve gone through three approaches to generate a random alphanumeric string in Kotlin, exploring the nuances of each. Then, we shifted gears to examine a high-performance solution that can be repurposed for the Kotlin and Java APIs.
As always, the code can be found over on GitHub.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Random string generator functions for Kotlin multiplatform
License
lamba92/KRandomStrings
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Common code library of extension functions for kotlin.random.Random object adding random strings and UUIDv4
Jitpack cannot build for MacOS or Windows so for now that’s it folks.
val uuid: String = Random.uuid() // 478b9e1c-a428-48e3-9f1f-af14e4deffcb val alhpanum: String = Random.nextAlphanumericString() // abcdefghijk1234 val char: Char = Random.nextChar()
Check the here for other functions.
Add the JitPack.io repository to the project build.grade :
Then import the latest version in the build.gradle of the modules you need:
If using Gradle Kotlin DSL:
repositories < maven(url = "https://jitpack.io") >. dependencies < implementation("com.github.lamba92.krandomstrings", "KRandomStrings", "") >
The -platform placeholder should be replaced with:
Leave it empty for common sources in common library.
About
Random string generator functions for Kotlin multiplatform
Создать случайную буквенно-цифровую строку в Kotlin
В этом руководстве мы обсудим, как сгенерировать случайную буквенно-цифровую строку в Kotlin, используя три разных подхода: Java Random , Kotlin Random и Apache Commons Lang RandomStringUtils .
Затем мы рассмотрим высокопроизводительный подход.
2. Зависимости
Прежде чем мы углубимся в руководство, давайте добавим зависимость Apache Commons Lang в наш pom.xml:
org.apache.commons commons-lang3 3.8.1
Кроме того, мы можем настроить некоторые константы для дальнейшего использования:
const val STRING_LENGTH = 10; const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+";
3. Java Random
Прежде всего, давайте посмотрим, как использовать Java Random для генерации случайной строки .
В этом примере мы будем использовать ThreadLocalRandom, который имеет экземпляр Random для каждого потока и защищает от конфликтов:
private val charPool : List = ('a'..'z') + ('A'..'Z') + ('0'..'9') @Test fun givenAStringLength_whenUsingJava_thenReturnAlphanumericString()
В этом примере мы получаем 10 случайных буквенно-цифровых символов из пула символов, генерируя их индексы, а затем объединяем их вместе, чтобы создать случайную строку.
ThreadLocalRandom доступен с JDK 7 . Вместо этого мы могли бы использовать java.util.Random . Но если несколько потоков используют один и тот же экземпляр Random , одно и то же начальное число используется несколькими потоками, вызывая конкуренцию потоков.
Однако ни ThreadLocalRandom, ни Random не являются криптографически безопасными , поскольку можно угадать следующее значение, возвращаемое генератором. Java действительно предоставляет заметно более медленный java.security.SecureRandom для безопасной генерации случайного значения.
4. Kotlin Random
Начиная с Kotlin 1.3, kotlin.random.Random доступен как многоплатформенная функция. Он использует java.util.Random в JDK 6 и 7, ThreadLocalRandom в JDK 8+ и Math.random в Javascript.
Таким же подходом мы можем получить случайную строку :
val randomString = (1..STRING_LENGTH) .map < i ->kotlin.random.Random.nextInt(0, charPool.size) > .map(charPool::get) .joinToString("");
5. Общий язык Apache
Наконец, если мы все еще используем Kotlin, мы можем использовать библиотеки Apache Common Lang для генерации случайной строки :
@Test fun givenAStringLength_whenUsingApacheCommon_thenReturnAlphanumericString()
В этом примере мы просто вызываем RandomStringUtils.randomAlphanumeric, чтобы получить нашу строку с предопределенной длиной.
Следует отметить, что RandomStringUtils генерирует случайные значения с помощью java.util.Random , что не является криптографически безопасным, как мы обсуждали выше. Итак, в случае создания защищенного токена или значения мы можем использовать CryptoRandom в Apache Commons Crypto или Java SecureRandom.
У нас есть руководство о том, как сгенерировать случайную строку в Java, а также более подробно осветить эту тему.
6. Производительность
Примечательным аспектом каждого из них является то, что он вызывает наш генератор случайных чисел STRING_LENGTH раз. Если мы создаем много строк или длинные строки, эти подходы могут быть слишком медленными. Однако с некоторыми дополнительными усилиями мы можем просто вызвать случайную последовательность байтов, а затем сопоставить их с нашим пулом символов:
@Test fun givenAStringLength_whenUsingRandomForBytes_thenReturnAlphanumericString() < val random = SecureRandom() val bytes = ByteArray(STRING_LENGTH) random.nextBytes(bytes) val randomString = (0..bytes.size - 1) .map < i ->charPool[random.nextInt(charPool.size)] >.joinToString("") assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) assertEquals(STRING_LENGTH, randomString.length) >
Что делает этот подход мощным, так это то, что, хотя мы все еще выполняем поиск STRING_LENGTH в нашем charPool , мы вызываем наш случайный генератор только один раз. И, помимо того, что это быстрее, это также может уменьшить конкуренцию потоков в общих экземплярах.
7. Заключение
В заключение мы рассмотрели три подхода к генерации случайной буквенно-цифровой строки в Kotlin, исследуя нюансы каждого из них. Затем мы переключились, чтобы изучить высокопроизводительное решение, которое можно перепрофилировать для API Kotlin и Java.
Как всегда, код можно найти на GitHub.