using dollar :
Iterable<Character> chars = $('a', 'z'); // 'a', 'b', c, d .. z
given chars you can create a "shuffled" range of characters:
Iterable<Character> shuffledChars = $('a', 'z').shuffle();
then taking the first characters of n , you get a random string of length n . The final code is simple:
public String randomString(int n) { return $('a', 'z').shuffle().slice(n).toString(); }
NB : condition n > 0 crossed out slice
EDIT
as Steve correctly pointed out, randomString uses no more than once each letter. As a workaround, you can repeat the alphabet m times before calling shuffle :
public String randomStringWithRepetitions(int n) { return $('a', 'z').repeat(10).shuffle().slice(n).toString(); }
or just specify your alphabet as String :
public String randomStringFromAlphabet(String alphabet, int n) { return $(alphabet).shuffle().slice(n).toString(); } String s = randomStringFromAlphabet("00001111", 4);
dfa Apr 13 2018-10-10T00: 00Z
source share