A Stream
might be useful in this case:
final Random rand = new Random();
String str = "string";
str = Stream.of(str.split("")).map(
x -> x + Integer.valueOf(rand.nextInt(10))
).collect(Collectors.joining());
System.out.println(str); // s8t9r6i0n1g6
We get a stream of individual letters in the string, and add a random number to each string. Finally we join everything together to get a final string.
A small update. Since java-8 String
class has chars
methods which returns a stream of character. So we can use it directly without splitting the original string. For example:
Random rand = new Random();
String str = "string";
str = str.chars().mapToObj(
c -> String.valueOf((char)c) + rand.nextInt(10)
).collect(Collectors.joining());
System.out.println(str); // s5t7r8i4n3g1