To shuffle a string in Java, you can use the shuffle
method of the Collections
class and pass it a List
containing the characters of the string.
Here's an example of how you can do this:
import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { String s = "abcdefghijklmnopqrstuvwxyz"; List<Character> characters = s.chars().mapToObj(c -> (char) c).collect(Collectors.toList()); Collections.shuffle(characters); String shuffled = characters.stream().map(Object::toString).collect(Collectors.joining()); System.out.println(shuffled); } }
This code will shuffle the characters of the string using the shuffle
method of the Collections
class, and then create a new string by joining the shuffled characters together using the stream
and collect
methods.
You can also use the shuffle
method of the Collections
class to shuffle the characters of a StringBuilder
or StringBuffer
object, if you need to shuffle a string in-place:
import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abcdefghijklmnopqrstuvwxyz"); List<Character> characters = sb.chars().mapToObj(c -> (char) c).collect(Collectors.toList()); Collections.shuffle(characters); sb.setLength(0); characters.forEach(sb::append); System.out.println(sb); } }
This code will shuffle the characters of the StringBuilder
object in-place and print the shuffled string to the console.