Quantcast
Channel: How to generate a random alpha-numeric string - Stack Overflow
Viewing all articles
Browse latest Browse all 48

Answer by F_SO_K for How to generate a random alpha-numeric string

$
0
0

You can do this in one line with no external libraries.

int length = 12;String randomString = new Random().ints(48, 122).filter(i -> (i < 58 || i > 64) && (i < 91 || i > 96)).limit(length).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();System.out.print(randomString);

I have separated out the length into a parameter, and added a line to print the result.

This code creates a stream of random integers bounded to the alphanumeric ascii range. It then filters out some symbols, because the alphanumeric range is not continuous. It then limits the length and collects the result into a string.

Because this approach discards something like 20% of the numbers/characters it generates (as they are symbols), there is a small performance impact.

I don't find it particularly readable, but I don't think anyone else has suggested a native Java solution in one line.


Viewing all articles
Browse latest Browse all 48

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>