Java
String Manipulation
String Sorting
Java Programming
Coding Tutorial

Sort a single String in Java

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Sorting a single string in Java is a common operation that can be useful in various scenarios such as organizing characters alphabetically, checking for anagrams, or simplifying the process of finding duplicate characters. This article explains how to sort a string in Java using different approaches, provides examples, and includes a table summarizing key points.

Technical Explanation

In Java, a string is essentially a sequence of characters. To sort this sequence, the string must first be converted to a data structure that allows for sorting operations. The most common approach is to convert the string to a character array, sort the array, and convert it back to a string.

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

The simplest way to sort a string alphabetically in Java entails using the toCharArray() method to convert the string into an array of characters and then applying Arrays.sort() to sort the characters.

java
1import java.util.Arrays;
2
3public class SortStringExample {
4    public static void main(String[] args) {
5        String original = "sortme";
6        char[] charArray = original.toCharArray();
7        
8        Arrays.sort(charArray);
9        
10        String sorted = new String(charArray);
11        System.out.println("Sorted string: " + sorted);
12    }
13}

Explanation:

  1. Convert to Char Array: Use toCharArray() to transform the string into a char[].
  2. Sort Array: Use Arrays.sort() to sort the char[] in ascending order based on Unicode values.
  3. Convert Back to String: Create a new String from the sorted char[].

Method 2: Using Streams

Java 8 introduced Streams, which can be utilized to sort characters within a string using a more functional approach.

java
1import java.util.stream.Collectors;
2
3public class SortStringWithStreams {
4    public static void main(String[] args) {
5        String original = "sortme";
6        
7        String sorted = original.chars()
8                                .sorted()
9                                .mapToObj(c -> String.valueOf((char) c))
10                                .collect(Collectors.joining());
11        
12        System.out.println("Sorted string: " + sorted);
13    }
14}

Explanation:

  1. Character Stream: Obtain an IntStream using chars().
  2. Sort the Stream: Use sorted() to sort the characters.
  3. Map and Collect: Convert each int back to char, then to String, and finally collect the results using Collectors.joining().

Performance Considerations

  • Time Complexity: Sorting algorithms implemented in Java, like TimSort used by Arrays.sort(), perform in O(nlogn)O(n \log n) time complexity.
  • Space Complexity: Both methods require additional space to store the character array or intermediate streams.

Table: Key Points for Sorting a String

StepMethod 1: Arrays.sort()Method 2: Streams
ConversiontoCharArray().chars() (returns IntStream)
Sorting MechanismArrays.sort().sorted()
Conversion Backnew String(charArray).mapToObj() + Collectors.joining()
ComplexityTime: O(nlogn)O(n \log n) Space: O(n)O(n)Time: O(nlogn)O(n \log n) Space: O(n)O(n)

Additional Details

Handling Case Sensitivity

Sorting by default is case-sensitive and sorts capital letters before lowercase ones. To perform a case-insensitive sort, convert the string to all lowercase or uppercase before sorting:

java
String lowerCaseSorted = original.toLowerCase();

Sorting with Custom Order

Sometimes a different sorting order is required, like sorting in descending order. Implement a custom comparator for such cases.

java
1import java.util.Arrays;
2import java.util.Collections;
3
4public class CustomSortExample {
5    public static void main(String[] args) {
6        String original = "sortme";
7        Character[] charArray = original.chars()
8                                        .mapToObj(c -> (char)c)
9                                        .toArray(Character[]::new);
10        
11        Arrays.sort(charArray, Collections.reverseOrder());
12        
13        String sorted = Arrays.stream(charArray)
14                              .map(String::valueOf)
15                              .collect(Collectors.joining());
16        
17        System.out.println("Custom sorted string: " + sorted);
18    }
19}

Dealing with Unicode and Internationalization

When dealing with international characters, consider using Collator from java.text package to ensure locale-sensitive comparisons.

java
1import java.text.Collator;
2import java.util.Arrays;
3import java.util.Locale;
4
5public class InternationalSortExample {
6    public static void main(String[] args) {
7        String original = "éàçü";
8        Character[] charArray = original.chars()
9                                        .mapToObj(c -> (char)c)
10                                        .toArray(Character[]::new);
11        
12        Collator collator = Collator.getInstance(new Locale("fr", "FR"));
13        Arrays.sort(charArray, collator::compare);
14        
15        String sorted = Arrays.stream(charArray)
16                              .map(String::valueOf)
17                              .collect(Collectors.joining());
18        
19        System.out.println("Internationally sorted string: " + sorted);
20    }
21}

Conclusion

Sorting a string in Java is a straightforward task that can be accomplished in various ways, ranging from conventional approaches using arrays to modern functional programming techniques using streams. The method chosen depends on the specific requirements, such as case-sensitivity and locale considerations. By understanding these strategies, developers can make informed decisions on how to manipulate and sort strings effectively.


Course illustration
Course illustration

All Rights Reserved.