Java Code Examples: Utility classes
Random Values
Random Integer
new Random().nextInt(min, max+1) return [min, max]
// Java 8 |
// Java 1.7 or later |
// Before Java 1.7 |
Math.random() return [0, 1)
Random.nextInt(n)
is more efficient thanMath.random() * n
Math.random() uses Random.nextDouble() internally. Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
int randomNum = min + (int) (Math.random() * ((max - min) + 1)); |
Random float
// TODO
Random String
// TODO
Regex Expression
matches()
- Checks if the regexp matches the complete string.
String source = "hello there, I am a Java developer. She is a Web developer."; |
find()
- Get matching substrings
String source = "hello there, I am a Java developer. She is a Web developer."; |
Replace group string
String source = "hello there, I am a Java developer. She is a Web developer."; |
Non-greedy regular expression
Followed by the ?. For example .*?
Match special characters
[\\special_character] |
For example:
[\\(\\)\\[\\]] |
Match multiple line string
// Pattern.DOTALL |
Match case-insensitive string
// Pattern.CASE_INSENSITIVE |
// (?i) enables case-insensitivity |
// convert string cases |
Multiple flags
Pattern.compile("regexStr", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); |