Sort a single String in Java

Markus picture Markus · Mar 3, 2009 · Viewed 291.8k times · Source

Is there a native way to sort a String by its contents in java? E.g.

String s = "edcba"  ->  "abcde"

Answer

Jon Skeet picture Jon Skeet · Mar 3, 2009

toCharArray followed by Arrays.sort followed by a String constructor call:

import java.util.Arrays;

public class Test
{
    public static void main(String[] args)
    {
        String original = "edcba";
        char[] chars = original.toCharArray();
        Arrays.sort(chars);
        String sorted = new String(chars);
        System.out.println(sorted);
    }
}

EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.