Sort ArrayList alphabetically

Posted by relyt on Stack Overflow See other posts from Stack Overflow or by relyt
Published on 2010-03-23T00:56:16Z Indexed on 2010/03/23 1:01 UTC
Read the original article Hit count: 540

Filed under:
|
|

I'm trying to find all permutations of a string and sort them alphabetically.

This is what I have so far:

public class permutations {

        public static void main(String args[]) {
            Scanner s = new Scanner(System.in);
            System.out.print("Enter String: ");
            String chars = s.next();
            findPerms("", chars);
        }

        public static void findPerms(String mystr, String chars) {

            List<String> permsList = new ArrayList<String>();

                if (chars.length() <= 1)
                        permsList.add(mystr + chars);
                        //System.out.print(mystr + chars + " ");

                else
                        for (int i = 0; i < chars.length(); i++) {
                            String newString = chars.substring(0, i) + chars.substring(i + 1);
                            findPerms(mystr + chars.charAt(i), newString);
                        }

               Collections.sort(permsList);

               for(int i=0; i<permsList.size(); i++) {
                    System.out.print(permsList.get(i) + " ");
               }
       }
}

IF I enter a string "toys" I get:

toys tosy tyos tyso tsoy tsyo otys otsy oyts oyst osty osyt ytos ytso yots yost ysto ysot stoy styo soty soyt syto syot

What am I doing wrong. How can I get them in alphabetical order? Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about arraylist