Extract a Random instance to a variable (#1942)
This commit is contained in:
parent
0ce35bb11e
commit
7c6536685c
|
@ -2,23 +2,23 @@ package com.baeldung.string;
|
||||||
|
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
public class StringHelper {
|
class StringHelper {
|
||||||
public static String removeLastChar(String s) {
|
static String removeLastChar(String s) {
|
||||||
return (s == null || s.length() == 0) ? s : (s.substring(0, s.length() - 1));
|
return (s == null || s.length() == 0) ? s : (s.substring(0, s.length() - 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String removeLastCharRegex(String s) {
|
static String removeLastCharRegex(String s) {
|
||||||
return (s == null) ? s : s.replaceAll(".$", "");
|
return (s == null) ? s : s.replaceAll(".$", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String removeLastCharOptional(String s) {
|
static String removeLastCharOptional(String s) {
|
||||||
return Optional.ofNullable(s)
|
return Optional.ofNullable(s)
|
||||||
.filter(str -> str.length() != 0)
|
.filter(str -> str.length() != 0)
|
||||||
.map(str -> str.substring(0, str.length() - 1))
|
.map(str -> str.substring(0, str.length() - 1))
|
||||||
.orElse(s);
|
.orElse(s);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String removeLastCharRegexOptional(String s) {
|
static String removeLastCharRegexOptional(String s) {
|
||||||
return Optional.ofNullable(s)
|
return Optional.ofNullable(s)
|
||||||
.map(str -> str.replaceAll(".$", ""))
|
.map(str -> str.replaceAll(".$", ""))
|
||||||
.orElse(s);
|
.orElse(s);
|
||||||
|
|
|
@ -167,9 +167,11 @@ public class JavaRandomUnitTest {
|
||||||
final int leftLimit = 97; // letter 'a'
|
final int leftLimit = 97; // letter 'a'
|
||||||
final int rightLimit = 122; // letter 'z'
|
final int rightLimit = 122; // letter 'z'
|
||||||
final int targetStringLength = 10;
|
final int targetStringLength = 10;
|
||||||
|
final Random random = new Random();
|
||||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||||
|
|
||||||
for (int i = 0; i < targetStringLength; i++) {
|
for (int i = 0; i < targetStringLength; i++) {
|
||||||
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1));
|
final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
||||||
buffer.append((char) randomLimitedInt);
|
buffer.append((char) randomLimitedInt);
|
||||||
}
|
}
|
||||||
final String generatedString = buffer.toString();
|
final String generatedString = buffer.toString();
|
||||||
|
|
Loading…
Reference in New Issue