I'd like a nice one line way of generating a random permutation of a Java String.
Here is an example using Java 8 Streams, of the direction I'm looking for.
In this example I am Using "abcd" as an example input, which could produce permutations like dabc, dbac, etc.
I've reduced generating the String permutation to three lines, but I have a feeling it could be shorter.
public static void main(String[] args) {
List<Character> charList = "abcd".chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Collections.shuffle(charList);
String string = charList.stream().map(String::valueOf).collect(Collectors.joining());
System.out.println(string);
}
Any way to make this code shorter / simpler would be appreciated.
EDIT:
OK, I have come up with what I think is an efficient one line solution, but it is not very readable, so I will probably break it down to a few lines.
I am including it here just for reference. If someone can simplify it, that would be a welcome answer as well.
String str = "ABCDE";
String str2 = str.chars().mapToObj(e->(char)e).collect(Collectors.toMap(key -> new Random().nextInt(), value -> value)).values().stream().map(String::valueOf).collect(Collectors.joining());
System.out.println(str2);