1

I need to create a method to geneate random (single) letter and return it as String, not as a char.
I saw solutions like this creating random char. But I need my method to return a String type.
I managed to build the following method:

public static String randomLetter(){
    int num = intInRange(0, 26) + 97;
    char [] temp = new char[1];
    temp[0] = (char) num;
    return new String(temp);
}

Based on already existing method in our project

public static int intInRange(int min, int max) {
    Random rnd = new Random();
    return rnd.nextInt(max - min) + min;
}

But I do not like what I currently have since I'm creating too many temporary variables to achieve the goal.
Is there a way to get similar result in a shorter way to avoid usage of char [] temp ?

Prophet
  • 32,350
  • 22
  • 54
  • 79

2 Answers2

2

Wouldn't it be more useful to be able to return a String of any length, including 1? If so, you could do something like the following:

public static String randomString(int length) {
    return new Random().
        ints('A', 'z').
        filter(Character::isLetter).
        limit(length).
        collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).
        toString();
}
g00se
  • 3,207
  • 2
  • 5
  • 9
1

Try it like this. First cast the returned int as a char and then append "" to convert to a String.

public static String randomLetter() { 
   return (char)(intInRange('a', 'z'+1)) +"";
}

Since String.valueOf() first boxes the char to Character and then calls String.valueOf() on that object, I would just call Character.toString() directly and avoid the extra overhead.

public static String randomLetter() {
    return  Character.toString(intInRange('a', 'z'+1));
}
WJS
  • 36,363
  • 4
  • 24
  • 39