Open In App

How to Shuffle Characters in a String in Java?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to shuffle characters in a String by using Java programming. For this, we have taken a String value as input and the method is available in java.util package and this method takes a list as input.

Steps to shuffle characters in a String in Java

  • First, take one String value.
  • After that convert this string to the character array.
  • Then shuffle the characters in the character array by using the Collections.shuffle() method.
  • After that create an object for the StringBuilder class, then append the result to the StringBuilder object.
  • Then this object is converted into a String value.
  • Finally display the result.

Java Program Shuffle characters in a String

Here, we have taken one Java class. After that, in the main class, we have created shuffleString(String input). This method takes one String value as an argument. After that this String value is converted into a character array then shuffle the characters by using the Collections.shuffle method. This result appends to the StringBuilder class object and finally prints the required result.

Below is the implementation of the above-mentioned topic:

Java




// Java Program to demonstrate
// Shuffling characters in a String
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
  
// Driver Class
public class ShuffleStringExample {
    public static String shuffleString(String input) {
        
        // Convert String to a list of Characters
        List<Character> characters = new ArrayList<>();
        for (char c : input.toCharArray()) {
            characters.add(c);
        }
  
        // Shuffle the list
        Collections.shuffle(characters);
  
        // Convert the list back to String
        StringBuilder shuffledString = new StringBuilder();
        for (char c : characters) {
            shuffledString.append(c);
        }
  
        return shuffledString.toString();
    }
  
    public static void main(String[] args) {
        // Example usage
        String originalString = "GeeksForGeeks";
        String shuffledString = shuffleString(originalString);
  
        System.out.println("Original String: " + originalString);
        System.out.println("Shuffled String: " + shuffledString);
    }
}


Output in console:

Console Output

Explanation of the above Program:

  • In above example we have written logic for shuffling characters in a String value.
  • In java we have Collections.shuffle method, this method take list as input.
  • This method can be able to shuffle the characters in character array then this result appends to StringBuilder class object after that we have converted this object into String value then finally, it prints the result as output.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads