How to Shuffle a String in Java [2 ways]

In this post I will be sharing how to shuffle a String in java with examples. There are two ways to achieve our goal. First, using shuffle method in the Collections class of util package. Second, using Random class.

Read Also:  Count number of commas in String in Java

1. Using Shuffle method [java.util.Collections.shuffle()]

It is a method of a Collections class that takes a list as the parameter and shuffles the elements of the list randomly. "UnsupportedOperationException" is thrown if the list given in the parameter section does not support the set operation.

1.1 Parameters of the Shuffle method


Syntax: Shuffle (List list, Random ran)
First parameter: list is the list that needs to be shuffled
Second parameter: ran is the randomness source to shuffle the list

Let us understand the functioning of the shuffle method with the help of an example before moving for our target to shuffle a string.

Example

import java.util.*;
public class ShuffleStringOne
{
 	public static void main(String[] args)
    	{
        	ArrayList<String>  list = new ArrayList<String>();
        	list.add("cat");
        	list.add("dog");
        	list.add("cow");
        	list.add("bull");
       		list.add("snake");
        	list.add("goat");
        	// List before shuffling
       		System.out.println("Original List : \n" + list);
  
        	// Second parameter will be Random()
        	Collections.shuffle(list, new Random());
        	System.out.println("\nShuffled List with Random() : \n" + list);
  
       		// Second parameter will be Random(2).
       		Collections.shuffle(list, new Random(2));
        	System.out.println("\nShuffled List with Random(2) : \n" + list);
  
        	// Second parameter will be Random(4).
        	Collections.shuffle(list, new Random(4));
        	System.out.println("\nShuffled List with Random(4) : \n" + list);
  
    	}
}


Output:

Original List :
[cat, dog, cow, bull, snake, goat]

Shuffled List with Random() :
[cow, bull, goat, dog, snake, cat]

Shuffled List with Random(2) :
[cat, cow, bull, dog, goat, snake]

Shuffled List with Random(4) :
[cat, goat, cow, dog, snake, bull]


Here we can observe that the list we provided is shuffled. So for shuffling using the shuffle method, we compulsorily need a list to pass as the parameter.

In the above example, we initialized a list and added elements to that list. And with the help of Collection.shuffle() we got the shuffled list. Now for applying the shuffle method to solve the problem of shuffling a string, firstly we need a list in order to use the shuffle method. So we need to convert the string into a list with each character of the string as the individual elements of the list.

For converting a string into a list we need to use the split method for individually considering each character of the string and using the asList method to create a list out of it. To better understand this concept, the example for it is given below.


import java.util.*;
public class ShuffleStringTwo 
{
 public static void main(String[] args)
{
  		String str="abcd";
  		List<String> letters = Arrays.asList(str.split(""));
  		System.out.println(letters);
  	}
}
Output:
[a, b, c, d]



So here in the above example, we converted the string "abcd" into the list with each character of the string as a distinct element of the list. Now we can apply the shuffle method on the list and get the shuffled form of the list and then combining the elements of the list to a string will give us our desired output.

Java Program to Shuffle a String Using shuffle() method


import java.util.*;
public class ShuffleStringExample
 {
  	public static void main(String[] args)
{
 		String str="abcd";
  		List<String> characters = Arrays.asList(str.split(""));
 		Collections.shuffle(characters);
  		String afterShuffle = "";
  		for (String character : characters)
{
    			afterShuffle += character;
  		}
  		System.out.println(afterShuffle); 
 	 }
}



Output:
cbda

2. Using Random method

The word shuffle means to randomly arrange the characters, and for generating random values we have a random method that we can take into use for shuffling a string.

Random

It is a class of util package. For using the random class refer to the example given below:

import java.util.Random;
class RandomExample {
    public static void main( String args[] ) {
     //creating an instance of random class
      Random rand = new Random(); 
      //for specifying the range of the numbers
      int maxLimit = 25;
      int r1 = rand.nextInt(maxLimit); 
      double r2=rand.nextDouble();
      float r3=rand.nextFloat();
      //Printing the values 
      System.out.println("Random integer value from 0 to" + (maxLimit-1) + " : "+ r1);
      System.out.println("Random float value between 0.0 and 1.0 : "+r2);
      System.out.println("Random double value between 0.0 and 1.0 : "+r3);
    }
}

Output:
Random integer value from 0 to 24 : 17
Random float value between 0.0 and 1.0 : 0.9625353493043718
Random double value between 0.0 and 1.0 : 0.07440293

So using this we can generate random index numbers and access random characters of the strings through the index numbers generated by the Random class.

Java Program to Shuffle a String Using Random Class [Java 7]



import java.util.*;

public class ShuffleStringExampleTwo { 
	public static String ShuffleString(String text) {
        List<Character> alpha = new LinkedList<>();
        for(char c:text.toCharArray()){
            alpha.add(c);
        }
        StringBuilder ans = new StringBuilder();
        for (int i=0;i<text.length();i++){
            int randomPosition = new Random().nextInt(alpha.size());
            ans.append(alpha.get(randomPosition));
            alpha.remove(randomPosition);
        }
        return ans.toString();
    }
  public static void main(String[] args){
    System.out.println(ShuffleString("abcd"));
  }
}

Output:
dcba

The above code is compatible to be executed on the Java7 version but if we want to avoid the loop in the code, Java8 provide the advantage of the stream feature.

Java Program to Shuffle a String Using Random Class [Java 8]


import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ShuffleStringExampleThree 
{    
	public static String StringShuffle(String text)
  {
        List<Character> alpha =  text.chars().mapToObj( c -> (char)c).collect(Collectors.toList());
        StringBuilder ans = new StringBuilder();
        IntStream.range(0,text.length()).forEach((index) -> {
            int rand = new Random().nextInt(alpha.size());
            ans.append(alpha.get(rand));
            alpha.remove(rand);
        });
        return ans.toString();
  }
  public static void main(String[] args){
    System.out.println(StringShuffle("abcd"));
  }
}

Output:
bacd

Hence, there can be different methods to solve the problem of shuffling a string, but these were two easy and basic ways to solve the problem.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry