HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Sorting a String based on its words

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortingwordsitsbasedstring

Problem

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<strArray.length; i++){
        sb.append(strArray[i]);
        sb.append(" ");
    }
    return sb.toString();
}

Solution

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<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 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.

Code Snippets

private static final Pattern PATTERN = Pattern.compile("\\s+");
String[] strArray = PATTERN.split(s);
for (int i=0; i<strArray.length; i++){
    sb.append(strArray[i]);
for (String str : strArray){
    sb.append(str);
public static String sortString(String s){
    return PATTERN.splitAsStream(s).sorted().collect(Collectors.joining(" "));
}

Context

StackExchange Code Review Q#125395, answer score: 7

Revisions (0)

No revisions yet.