RandomTools Tutorial
RandomTools is a utility class for generating various types of random values, including numbers, strings, and UUIDs (with version 7 support).
Main Features
- Thread-safe random generation: Uses
ThreadLocalRandomfor high performance - Cryptographic-strength randomness: Uses
SecureRandomfor security-level randomness - Multiple random value generation: Supports numbers, strings, UUIDv7, etc.
- Time-ordered UUIDs: UUIDv7 provides better locality than random UUIDs
Number Random Generation
1. Generate Six-Digit Numbers
// Generate a six-digit random number (100000-999999)
int number = RandomTools.generateNumber();
System.out.println(number); // e.g.: 456789
2. Generate Numbers with Specified Digits
// Generate random numbers with specified digit count
int threeDigit = RandomTools.generateNumber(3); // 100-999
int fourDigit = RandomTools.generateNumber(4); // 1000-9999
System.out.println(threeDigit); // e.g.: 567
System.out.println(fourDigit); // e.g.: 3456
String Random Generation
1. Generate Six-Character Random String
// Generate a six-character alphanumeric random string
String randomStr = RandomTools.generateRandomString();
System.out.println(randomStr); // e.g.: aB3xY9
2. Generate Random String with Specified Length
// Generate random strings with specified length
String shortStr = RandomTools.generateRandomString(3);
String longStr = RandomTools.generateRandomString(10);
System.out.println(shortStr); // e.g.: Xy2
System.out.println(longStr); // e.g.: AbC3dE5fGh
UUID Generation
1. Generate UUIDv7
// Generate UUID version 7 (time-ordered)
UUID uuid = RandomTools.uuid();
System.out.println(uuid); // e.g.: 550e8400-e29b-41d4-a716-446655440000
2. Generate UUIDv7 String Without Hyphens
// Generate UUID string without hyphens
String uuidStr = RandomTools.uuidStr();
System.out.println(uuidStr); // e.g.: 550e8400e29b41d4a716446655440000
3. View Timestamp of UUID
// Get timestamp information from UUIDv7
String uuidString = RandomTools.uuidStr();
Date timestamp = RandomTools.showTime(uuidString);
System.out.println(timestamp); // e.g.: Wed Oct 25 14:30:45 CST 2023
Notes
- All generation methods are static and can be called directly through the class name
- Number generation uses
ThreadLocalRandomto ensure thread safety and performance - UUIDv7 is time-ordered and has better database indexing performance
- String generation uses a fixed alphanumeric character pool