Sort a single String in Java

Learn sort a single string in java with practical examples, diagrams, and best practices. Covers java, string, sorting development techniques with visual explanations.

How to Sort a Single String in Java: A Comprehensive Guide

How to Sort a Single String in Java: A Comprehensive Guide

Learn various methods to sort characters within a Java String, from basic array manipulation to advanced Stream API techniques, ensuring your strings are always in order.

Sorting a String in Java isn't as straightforward as sorting a collection of objects because String objects are immutable. This means you cannot directly modify the characters within a String. Instead, you typically convert the String into a mutable character array, sort the array, and then convert it back into a String. This article explores several common and efficient ways to achieve this, catering to different Java versions and programming styles.

Method 1: Using toCharArray() and Arrays.sort()

This is the most common and arguably the simplest method for sorting a String in Java. It involves converting the String into a char array, sorting the array using Arrays.sort(), and then reconstructing the String from the sorted char array. This method is efficient and easy to understand.

import java.util.Arrays;

public class SortStringSimple {
    public static String sortString(String inputString) {
        char[] tempArray = inputString.toCharArray();
        Arrays.sort(tempArray);
        return new String(tempArray);
    }

    public static void main(String[] args) {
        String originalString = "java";
        String sortedString = sortString(originalString);
        System.out.println("Original String: " + originalString);
        System.out.println("Sorted String: " + sortedString);
        
        originalString = "programming";
        sortedString = sortString(originalString);
        System.out.println("Original String: " + originalString);
        System.out.println("Sorted String: " + sortedString);
    }
}

Basic string sorting using toCharArray() and Arrays.sort().

Method 2: Using Java 8 Streams for Sorting

For more functional programming enthusiasts or when working with Java 8 and newer, the Stream API provides a concise way to sort characters. This method involves converting the String to an IntStream of character codes, sorting them, and then collecting them back into a String using a StringBuilder.

import java.util.stream.Collectors;

public class SortStringStreams {
    public static String sortString(String inputString) {
        return inputString.chars()
                          .sorted()
                          .collect(StringBuilder::new,
                                   StringBuilder::appendCodePoint,
                                   StringBuilder::append)
                          .toString();
    }

    public static void main(String[] args) {
        String originalString = "helloWorld";
        String sortedString = sortString(originalString);
        System.out.println("Original String: " + originalString);
        System.out.println("Sorted String: " + sortedString);

        originalString = "Zebra";
        sortedString = sortString(originalString);
        System.out.println("Original String: " + originalString);
        System.out.println("Sorted String: " + sortedString);
    }
}

Sorting a String using Java 8 Streams.

A flowchart diagram showing the process of sorting a string using Java Streams. The steps are: Start -> Convert String to IntStream of characters -> Sort IntStream -> Collect characters into StringBuilder -> Convert StringBuilder to String -> End. Use light blue rectangles for processes and arrows for flow.

Workflow of String sorting using Java Streams.

Method 3: Sorting with Collections.sort() (for List<Character>)

While less direct than Arrays.sort(), this method is useful if you prefer working with List objects or need to apply custom sorting logic using a Comparator. You convert the String to a List<Character>, sort the list, and then reconstruct the String.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortStringCollections {
    public static String sortString(String inputString) {
        List<Character> chars = new ArrayList<>();
        for (char c : inputString.toCharArray()) {
            chars.add(c);
        }
        Collections.sort(chars);

        StringBuilder sb = new StringBuilder(chars.size());
        for (Character c : chars) {
            sb.append(c);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String originalString = "example";
        String sortedString = sortString(originalString);
        System.out.println("Original String: " + originalString);
        System.out.println("Sorted String: " + sortedString);

        originalString = "DataStructure";
        sortedString = sortString(originalString);
        System.out.println("Original String: " + originalString);
        System.out.println("Sorted String: " + sortedString);
    }
}

Sorting a String by converting to a List<Character>.