Compute All the Permutations of the String in Java

Exercise:

Write a Java Program to compute all the permutations of the string.

Click Here to View the Solution!
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Permutation{
    public static Set<String> getPermutation(String str) {
       
        //create a set to avoid duplicate permutation
        Set<String> permutations = new HashSet<String>();

        // check if string is null
        if (str == null)                
        {
            return null;
        }
        //terminating condition for recursion
        else if (str.length() == 0)      
        {
            permutations.add("");
            return permutations;
        }
        // get the first character
        char first = str.charAt(0);  

        // get the remaining substring
        String sub = str.substring(1);     
        Set<String> words = getPermutation(sub);

        for (String strNew : words) // access each element from words
        {
            for (int i = 0;i<=strNew.length();i++){
                permutations.add(strNew.substring(0, i) + first + strNew.substring(i));
            }
        }
        return permutations;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the string: ");
        String data = input.nextLine();
        System.out.println("Permutations of " + data + ": \n" + getPermutation(data));
    }
}
Click Here to View the Output!
Enter the string: asdf                                                                           
Permutations of asdf:                                                                            
[fsad, sfad, sdaf, fdsa, fasd, dafs, sfda, sadf, fads, dsfa, safd, asdf, sdfa, afds, fsda, dfas, 
adsf, dsaf, afsd, adfs, asfd, dasf, dfsa, fdas]    
Click Here to View the Explanation!
  • In this program, a recursive method called getPermutation() has been created. This method has a HashSet as its return type.
  • Inside this method, a HashSet called permutations has been initialized.
  • If the argument str is null, then null is return, or if the argument is of length 0, then permutations is returned.
  • For every character in str the first and sub variables are initialized which contain the current character and the next remaining characters respectively.
  • The result of recursive calls to getPermutation() method is stored in the set words.
  • A for each loop is executed next which takes every element from words, creates its related permutation, and then adds it to the permutations HashSet.
  • The permutations set is then returned to the calling function in the main method of the program.
  • In the main method, a string called input is taken as an input from the user, using the Scanner class.
  • The possible permutations of this string are then displayed to the user using the getPermutation() method.