Sort a String in Java: Methods and Examples

Formulas & functions · Updated November 22, 2026

Java has no String.sort() method. To sort the characters in one string, convert it to a char[], call Arrays.sort(), and create a new string; to sort several strings, sort a collection or array with a comparator.

What “sorting a string” can mean

The phrase “sort a string” can describe two different tasks. You might want to reorder the individual characters in a single value, such as changing "banana" into "aaabnn". Or you might have multiple words or names and want to arrange those complete strings, such as sorting "pear", "apple", and "plum" into a list.

These operations use different Java tools. For characters, work with an array because a String is immutable: its contents cannot be rearranged in place. For a group of strings, use List.sort(), Arrays.sort(), or a stream, depending on how the data is stored and whether you need to keep the result.

It is useful to decide what “in order” means before writing code, too. Java’s default order is case-sensitive and based on UTF-16 code units. That is suitable for many programming tasks, but it may not match a reader’s idea of alphabetical order in a particular language.

Sort the characters in one string

For ordinary text made up of basic characters, convert the string to a character array, sort that array, and construct a new string from it:

import java.util.Arrays;

String input = "banana";
char[] characters = input.toCharArray();
Arrays.sort(characters);
String sorted = new String(characters);

System.out.println(sorted); // aaabnn

String.toCharArray() produces a new array, so sorting it does not change input. Arrays.sort(characters) puts the primitive char values in ascending numeric order. The constructor then makes a separate string from the sorted array. The example has three a characters, two n characters, and one b, so the result is "aaabnn".

This approach is concise and appropriate when the task really is to order Java char values. It also preserves duplicate characters: sorting is a rearrangement, not a process that removes repeated letters. If the goal is to find anagrams, this is a common way to create a normalized value for comparison, provided the same character and case rules are applied to both inputs.

Sort a list or array of strings

When each complete word is an item, sort the items rather than turning all the words into characters. For a mutable list, the usual choice is List.sort():

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

List<String> words = new ArrayList<>(
    List.of("pear", "apple", "plum")
);
words.sort(null);

System.out.println(words); // [apple, pear, plum]

Passing null as the comparator requests the elements’ natural order. The same sort can be written as words.sort(Comparator.naturalOrder()), which makes that choice explicit. List.sort() has been available since Java 8. The list itself is changed, so the example wraps List.of() in an ArrayList: lists created directly with List.of() are unmodifiable and cannot be sorted.

For an array, use Arrays.sort():

String[] words = {"pear", "apple", "plum"};
Arrays.sort(words);

System.out.println(Arrays.toString(words)); // [apple, pear, plum]

Both examples use Java’s natural string order, which is the same ordering used by String.compareTo(). This is lexicographic: Java compares corresponding positions from left to right, and the first unequal pair determines which string comes first. If one string is a prefix of the other, the shorter one comes first, so "app" precedes "apple".

Choose a different comparison rule

Natural ordering distinguishes uppercase and lowercase letters. It is not the same as sorting words in a dictionary, and its results can surprise people who expect all letters to be grouped without regard to case. For a simple case-insensitive comparison, use the built-in comparator:

words.sort(String.CASE_INSENSITIVE_ORDER);

This compares strings without distinguishing case for the comparison, but it does not convert the stored strings to lowercase. If two different strings compare as equal under that comparator, their relative order is retained by the stable list sort. For example, "Java" and "java" can compare as equal under this rule.

For ordering intended for people in a specific language or locale, use Collator rather than assuming that natural order is alphabetic:

import java.text.Collator;
import java.util.Locale;

Collator collator = Collator.getInstance(Locale.FRENCH);
words.sort(collator);

A collator applies locale-sensitive comparison rules, which can handle accents and other language conventions more appropriately than comparing raw character values. The right locale depends on the audience and the task. Locale-aware ordering is not a universal replacement for natural order: identifiers, file formats, and programming-language tokens often require a precise, locale-independent rule.

Sort Unicode text carefully

A Java char is a 16-bit UTF-16 code unit, not necessarily a complete Unicode character. Many common letters fit in one char, but some Unicode code points are represented by a pair of char values called a surrogate pair. Sorting the result of toCharArray() sorts those code units independently, so it can split or reorder a surrogate pair. That may corrupt text containing supplementary characters, such as many emoji.

If you need to sort Unicode code points instead, extract the code points, sort the integer values, and append them back as code points:

int[] codePoints = input.codePoints().toArray();
Arrays.sort(codePoints);

StringBuilder builder = new StringBuilder();
for (int codePoint : codePoints) {
    builder.appendCodePoint(codePoint);
}
String sortedByCodePoint = builder.toString();

This avoids treating the two halves of a surrogate pair as separate characters. However, code-point sorting still does not necessarily sort what a person sees as individual displayed symbols. A visible character can consist of multiple code points, such as a base letter followed by a combining accent; emoji can also be built from sequences of code points. Sorting the points independently can separate the parts of such a sequence. For human-facing text, consider whether the desired unit is a grapheme cluster (a user-perceived character) and whether locale-aware collation is more suitable than rearranging text at all.

Use streams when you need a new result

A stream can express a sort-and-collect operation without modifying the source list. This is useful when you want a sorted copy and want to leave the original order alone:

import java.util.List;

List<String> sortedWords = words.stream()
    .sorted()
    .toList();

Stream.toList() was added in Java 16 and returns an unmodifiable list. If the project uses an earlier Java version, or if the result must be mutable, collect into a list instead:

import java.util.stream.Collectors;

List<String> sortedWords = words.stream()
    .sorted()
    .collect(Collectors.toList());

Use sorted(comparator) when you need a non-default rule, for example words.stream().sorted(String.CASE_INSENSITIVE_ORDER). A stream operation does not sort the original collection; it produces sorted elements for the downstream operation. Choose the list method when changing the existing list is acceptable, and the stream approach when a separate result fits the surrounding code.

Common problems and practical choices

  • Calling a nonexistent method: String has no sort() method. Convert its characters to an array, or sort the collection that holds multiple strings.
  • Expecting the original string to change: Strings are immutable. Save the newly constructed string or sorted list in a variable if you need to use the result later.
  • Using an unmodifiable list: List.of(...) cannot be modified. Make a mutable copy before calling sort(), or use a stream to create a separate result.
  • Assuming default order ignores case: It does not. Choose a comparator when case-insensitive or locale-specific ordering is required.
  • Sorting arbitrary Unicode with char[]: This sorts UTF-16 code units and can damage surrogate pairs. Use code-point handling when that is the intended unit, and account for combining sequences when text is user-facing.
  • Encountering null elements: Natural ordering cannot compare a null string with a non-null string and will throw a NullPointerException. Decide how nulls should be handled; for example, use Comparator.nullsFirst(Comparator.naturalOrder()) if nulls should come first.

For a one-off sort, the built-in array and list methods are usually clearer than writing a sorting algorithm yourself. Their comparison-based sorting work grows roughly in proportion to n log n for n items, while converting a string to an array and rebuilding it also takes space proportional to the input length. A custom algorithm is generally only justified when a specialized ordering or data structure requires it.

Which method should you choose?

Use the data type and the meaning of “sorted” to guide the choice:

  • Reorder characters in a basic string: use toCharArray(), Arrays.sort(), and new String(...).
  • Reorder Unicode code points: use String.codePoints(), sort the resulting int[], and rebuild with appendCodePoint().
  • Sort an existing mutable list of words: call list.sort(comparator).
  • Sort a string array: call Arrays.sort(array, comparator), or the overload without a comparator for natural order.
  • Keep the source list unchanged: use a stream with sorted() and collect the output.
  • Sort for a language’s reading conventions: choose a suitable Collator and locale.

These choices prevent a common mismatch: sorting a list of words does not sort the letters inside each word, and sorting a word’s characters does not arrange a collection of words. State which unit you are ordering—code units, code points, visible characters, or whole strings—and the implementation becomes much easier to select correctly.

Frequently Asked Questions

Does Java have a built-in sort function for a String?
No. A String is immutable and has no sort() method. Convert its characters to an array and sort the array, or use a collection or array sorting method when sorting multiple strings.

How do I sort the letters in a string alphabetically?
For basic characters, call toCharArray(), sort with Arrays.sort(), then create a new string from the array. Keep in mind that the result follows character-value order, not necessarily dictionary order for a language.

How do I sort strings without regard to uppercase and lowercase?
For a list, use list.sort(String.CASE_INSENSITIVE_ORDER). For an array, use Arrays.sort(array, String.CASE_INSENSITIVE_ORDER). This changes comparison behavior, not the case of the strings themselves.

How do I sort a Java list alphabetically?
Call list.sort(null) or list.sort(Comparator.naturalOrder()) on a mutable list of non-null strings. The default is case-sensitive natural order; use a comparator for another rule.

Can I sort a string containing emoji with Arrays.sort()?
Sorting a char[] is unsafe for supplementary Unicode characters because it sorts UTF-16 code units separately. Sort code points instead if code-point order is what you need, while remembering that a displayed symbol may contain several code points.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.