Java port of the nanoid unique string ID generator.
A tiny, secure, URL-friendly, unique string ID generator for Java.
- Small. Just 1 class.
- Safe. It uses hardware random generator. Can be used in clusters.
- Short IDs. It uses a larger alphabet than UUID (A-Za-z0-9_-). So ID size was reduced from 36 to 21 symbols.
- Portable. Nano ID was ported to multiple programming languages.
This library is published to GitHub Packages. You'll need to configure your Maven or Gradle to access GitHub Packages.
Add the GitHub Packages repository to your pom.xml:
<repositories>
<repository>
<id>github</id>
<name>GitHub Packages</name>
<url>https://maven.pkg.github.com/albahrani/nanoid-java</url>
</repository>
</repositories>Then add the dependency:
<dependency>
<groupId>de.albahrani.nanoid</groupId>
<artifactId>nanoid-java</artifactId>
<version>1.1.0</version>
</dependency>Add the GitHub Packages repository to your build.gradle:
repositories {
maven {
name = "GitHubPackages"
url = uri("https://maven.pkg.github.com/albahrani/nanoid-java")
credentials {
username = project.findProperty("gpr.user") ?: System.getenv("USERNAME")
password = project.findProperty("gpr.key") ?: System.getenv("TOKEN")
}
}
}Then add the dependency:
dependencies {
implementation 'de.albahrani.nanoid:nanoid-java:1.1.0'
}import de.albahrani.nanoid.NanoId;
String id = NanoId.nanoid();
// Result: "K5urO4VjCU0LJEJmSGy0v"String id = NanoId.nanoid(10);
// Result: "jvqVeJJhBJ"String id = NanoId.customNanoid("ABCDEF", 10);
// Result: "FBAEFAADEB"Generate a URL-friendly unique ID. This method uses the URL-friendly alphabet A-Za-z0-9_- and returns an ID with 21 characters (to have a collision probability similar to UUID v4).
Generate a URL-friendly unique ID with custom length.
size- ID length
Generate unique ID with custom alphabet and length.
alphabet- Alphabet to use for ID generationsize- ID length
See Nano ID collision calculator for collision probability.
Nano ID is quite comparable to UUID v4 (random-based). It has a similar number of random bits in the ID (126 in Nano ID and 122 in UUID), so it has a similar collision probability:
For there to be a one in a billion chance of duplication, 103 trillion version 4 IDs must be generated.
There are three main differences between Nano ID and UUID v4:
- Nano ID uses a bigger alphabet, so a similar number of random bits are packed in just 21 symbols instead of 36.
- Nano ID code is smaller than
uuid/v4package: 130 bytes instead of 423. - Because of memory allocation tricks, Nano ID is 16% faster than UUID.
MIT License. See LICENSE for details.