Sort a String in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Strings are nothing but a sequence of characters. In certain situations, we need to reorder this sequence in such a way that its characters are arranged in lexicographically increasing or decreasing order. This is where the concept of sorting a string comes in.

Java has several ways to rearrange the characters inside the string in a particular order; many of them require it to be converted into an array of characters, like the Arrays.sort() and sorted() methods. Java has inbuilt methods to sort a string in any order, increasing or decreasing.

Introduction

A string is a collection of characters, including letters, numbers, symbols, and even spaces. To be recognized as a string in Java, it must be surrounded by double-quotes. For example, Scaler, How to sort a string in Java?, and' 123Random` are strings.

Strings in Java can be created using two ways.

  • String literal
  • Using new keyword

To get the desired output from our program, we frequently need to arrange the individual characters in strings in different orders. Sorting is the process of arranging a sequence (string in this case) based on desired criteria.

In other words, sorting a string is arranging its characters in increasing or decreasing order. Java provides methods like Arrays.sort(), reverseOrder() and sorted() to sort a string, which are covered in the subsequent sections.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Method 1: Arrays.sort() Method

In Java, the Arrays.sort() method is used to sort any array, whether it is an integer or a character array. To sort a String using this method:

  • Convert the input string into a char array using the toCharArray() method.
  • Sort the char array using Arrays.sort() method.
  • Finally convert the sorted array back to a String.

This Arrays.sort() method has the time complexity of O(NlogN)O(NlogN)

Example:

Output:

Custom sorting using Arrays.sort() method

Custom sorting allows us to modify the Arrays.sort() method's sorting criteria. Since we know that sorting is done based on ASCII values of characters, we can define custom logic to compare two characters and decide which one should come first.

The demonstration for the same is shown below, where we will be sorting the string "scaler" in reverse order.

  • Convert the input string into a Character array by creating a Character array of length equal to the string's size. Use a for loop to populate this array with the string's characters.
  • Pass one more parameter to the Arrays.sort() method, which is the Comparator, and override the default comparison criteria based on ASCII values.
  • Syntax of the compare() function to be used as Comparator:
  • The compare() function returns a negative value if o1 has to come first, positive if o2 has to come first, and 0 if they are the same.

Output:

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Method 2: Using Java 8 Streams and sorted() Method

Java 8 provides us with the Stream, which can sort any list using its built-in sorted() method. So we will need to convert the string into a list of characters using the chars() method first then sort it using the sorted() method.

Example:

Output

Explanation:

  • The example above sorts the String "Scaler" in alphabetically increasing order.
  • The inputstr is converted into the list of chars, which is then arranged in increasing alphabetical order using the sorted() method.
  • The collect() method takes the sorted object and passes it to the appendCodepoint() method of `[StringBuilder] ' (https://www.scaler.com/topics/java/stringbuilder-in-java/), which appends the string representation of each codepoint object to the sequence.
  • Finally, the toString() method is used to convert it into a string.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

Method 3: reverseOrder() Method

The reverseOrder() method of the Java Collections class is used to sort an array in lexicographically decreasing order. Because it is a static method, we can use the class name to call it directly.

  • Convert the input string into a Character array similar to what we have done above.
  • Pass a second argument to Arrays.sort() method as Collections.reverseOrder() which reverses the ordering of characters after sorting.
  • The array is first sorted in ascending order using the Arrays.sort() method. Then the natural ordering is reversed using the reverseOrder() method, resulting in a sorted array in descending order.

The syntax for reverseOrder():

Example:

Output

Explanation:

  • We have used the input string "scaler" string to demonstrate reverseOrder() method.
  • First, we convert the string into a Character array and then use the Arrays.sort() method, passing reverseOrder() as a comparator to rearrange it.
  • Convert it back to a String by applying the toString() method to the StringBuilder object sb.

Time Complexity: O(nlogn)O(n*log n)

Conclusion

  • Strings are a sequence of characters that can be rearranged in a particular order, such as lexicographically increasing or decreasing.
  • Strings in Java can be sorted using various methods such as:
    • Arrays.sort()
    • sorted() method (Java 8 Streams)
  • We can define custom comparators to arrange the characters of a string. These Comparators can be defined using the compare() function.
  • The Collections.reverseOrder() method can reverse-sort a string. It is passed as the second argument inside the Arrays.sort() method.
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more