Tuesday 23 June 2015

Java8: Generate a Random String in One Line

This is a program which demonstrates the power of Java 8 streaming to generate random strings in Java. It chains the filter, map, limit, and collect to turn random numbers into the required string.


The program will output random strings containing numbers [0-9] and letters [a-z,A-Z].


The numbers in the code map to UniCode characters (for a full Unicode chart see here).

An explanation of the code is as follows:

  1. Generate random numbers within the range 48 (unicode for 0) to 122 (unicode for z).
  2. Only allow numbers less than 57 (the digits 0-9) or greater than 65 and less than 90 (letters A-Z) or great than 97 (the letters A-Z).
  3. Map each number to a char.
  4. Stop when you have the required length of the string. 
  5. Collect the chars produced into a StringBuilder
  6. Turn the StringBuilder in a String and return


5 comments:

  1. For random.ints(48,122) upper bound should be 123, because it exclusive

    ReplyDelete
    Replies
    1. Also (i<57 || i>65) && (i <90 || i>97) should be
      (i < 58 || i > 64) && (i < 91 || i > 96)

      Delete
    2. finally, to avoid of unnecessary boxing and unboxing

      random.ints(48,123)
      .filter(i -> (i < 58) || (i > 64 && i < 91) || (i > 96))
      .limit(length)
      .collect(StringBuilder::new, (sb, i) -> sb.append((char) i), StringBuilder::append).toString());

      Delete
  2. I found an example of a script for a random number generator on the Internet, but I wanted to study this topic in more

    depth because in many my projects a random series exist and it will help to test the password or won accessed. I advise you to download random number generator java https://explainjava.com/random-number-generator-java/ and read the detailed article because simply copying the code, the effectiveness will of course be, but you'll not develop as a professional behind this.

    ReplyDelete