Sorting a String based on its words Is there a better, more efficient or nicer way to do this?

public static String sortString(String s){

    String[] strArray= s.split("\\s+");
    Arrays.sort(strArray);
    StringBuilder sb = new StringBuilder();
    for (int i=0; i&lt;strArray.length; i++){
        sb.append(strArray[i]);
        sb.append(" ");
    }
    return sb.toString();
}
A couple of comments:


String[] strArray = s.split("\\s+"); will create a Pattern object each time this is called, which might hurt the performance. It would be better to reuse the same pattern. Declare it as a constant:

private static final Pattern PATTERN = Pattern.compile("\\s+");


and then you can use 

String[] strArray = PATTERN.split(s);

Use a for-each loop instead of a loop using index. This is both easier to read and to maintain when you don't need the index. So instead of having 

for (int i=0; i&lt;strArray.length; i++){
    sb.append(strArray[i]);


you can have

for (String str : strArray){
    sb.append(str);





If you can use Java 8, you could have

public static String sortString(String s){
    return PATTERN.splitAsStream(s).sorted().collect(Collectors.joining(" "));
}


This splits the input String into a Stream&lt;String&gt; using splitAsStream. Then the stream is sorted and finally collected with a collector joining all elements together, separated by a space, using Collectors.joining(" "). As a side-note, this will not include the last white-space at the end of the joined Strings, unlike the code in your question.