Skip to content
Advertisement

Sort String of Characters Using Hashed Array and Java 8 Streams

I stumble upon this cool sorting algorithm with O(n) time complexity on GeeksforGeeks – Sort string of characters and I was trying to refactor the code to use Java Streams on the nested for loops instead and collect the result in a string variable but I can’t seem to wrap my head around it.

Here’s the original code:

// Java program to sort
// a string of characters
public class SortString{
    static final int MAX_CHAR = 26;
 
    // function to print string in sorted order
    static void sortString(String str) {
 
        // Hash array to keep count of characters.
        int letters[] = new int[MAX_CHAR];
 
        // Traverse string and increment
        // count of characters
        for (char x : str.toCharArray()) {
 
            // 'a'-'a' will be 0, 'b'-'a' will be 1,
            // so for location of character in count
            // array we will do str[i]-'a'.
            letters[x - 'a']++;
        }
        
        // HOW TO CONVERT THIS TO JAVA STREAM?  
        // Traverse the hash array and print
        // characters
        for (int i = 0; i < MAX_CHAR; i++) {
            for (int j = 0; j < letters[i]; j++) {
                System.out.print((char) (i + 'a'));
            }
        }
    }
 
    // Driver program to test above function
    public static void main(String[] args) {
        sortString("geeksforgeeks");
    }
}
// This code is contributed
// by Sinuhe

Advertisement

Answer

Try this.

static final int MAX_CHAR = 26;

static String sortString(String str) {
    int[] letters = new int[MAX_CHAR];
    str.chars().forEach(i -> letters[i - 'a']++);
    return IntStream.range(0, MAX_CHAR)
        .mapToObj(i -> Character.toString(i + 'a').repeat(letters[i]))
        .collect(Collectors.joining());
}

public static void main(String[] args) {
    System.out.println(sortString("geeksforgeeks"));
}

output:

eeeefggkkorss
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement