×

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java.

Introduction

Firstly, let us revise what is string

Strings are collections of characters that are frequently used in Java programming. Objects in the programming language Java include strings. For creating and manipulating strings, the Java platform offers the String class.

Although there is no method in the string class that explicitly sorts a string, we may nevertheless sort a string by using other techniques one after the other. A series of characters make up the string. String objects in Java are immutable, which simply means they can never be modified after they have been created.

There are two ways to create a string in java

  • By String Literal
  • By new Keyword

By String Literal

The syntax would be as follows

String s = “ Hello Man”;

By new Keyword

String s = new String(“Hello Man”);

Methods for sorting the string

In Java, there are two methods available for sorting any string.

  • Without sort() method
  • With sort() method

Without sort() method

Here, we'll lay out a method for sorting a string without of any specified reasoning. So, from the perspective of an interview, it does become a crucial strategy.

Process

  • By using toCharArray() method of a String class, convert a string to an array.
  • Now check for swapping array elements using nested loops.
  • Print the components of this character array.

Now let us write a simple java code that depicts the above procedure

File name: WithoutSort.java

// Java code that uses the toCharArray() function to alphabetically sort a string without //leveraging the sort() method


// importing the necessary classes
import java.io.*;
import java.util.Arrays;


class WithoutSort {
public static void main(String[] args) throws Exception
{
// separate string input
String str = "helloman";

// string to array conversion for computation
char arr[] = str.toCharArray();


// Nested loops enabling character comparison in the previous character array

char temp;


int i = 0;
while (i < arr.length) {
int j = i + 1;
while (j < arr.length) {
if (arr[j] < arr[i]) {

// evaluating each character individually
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j += 1;
}
i += 1;
}
// Now that the loop is finished, the entire array has been iterated.
System.out.println(arr);
}
}

Output

aehllmno

With sort() method

Process

  • The key logic is to use the String class' toCharArray() function on the input sequence to turn it into a character array.
  • To sort a character array, use the Arrays.sort(char c[]) method.
  • Create an arranged string from the char array using the constructor of the String class.

Now let us write a code for the above process

File name: WithSort.java

// Java code that uses the toCharArray() function to alphabetically sort a string The sort() //technique is employed here.
// Arrays class from the java.util package being imported
import java.util.Arrays;
public class WithSort {
// To sort a string alphabetically
public static String sortString(String inputString)
{
// raw string to character array conversion
char tempArray[] = inputString.toCharArray();
// utilizing temp array to sort
Arrays.sort(tempArray);
// providing a new, sorted string
return new String(tempArray);
}
public static void main(String[] args)
{
// individual string entered
String inputString = "helloman";
String outputString = sortString(inputString);
// Printing and displaying instructions
// Enter a string
System.out.println("Input String : " + inputString);
// Resulting string
System.out.println("Output String : "+ outputString);
}
}

Output

aehllmno

There is another procedure that is considered to be improved technique by using the sort() method only

Procedure

  • Raw string into character array conversion There isn't a simple way to do it. To populate the array, we'll use a for loop.
  • To sort a character array, use the Arrays.sort(T [], Comparator c) method. To achieve this, we must create the compare() methodology based on our unique sorting characteristics.
  • The Character array can now be converted to a String using StringBuilder.

The example program would be as follows

File name: WithSort1.java

// Sorting a Mixed String of Capital letters and Lower case letter Characters in Java
// importing the necessary classes
import java.util.Arrays;
import java.util.Comparator;


class WithSort1 {

public static String sortString(String inputString)
{
// converting a string input into a character array
Character tempArray[]
= new Character[inputString.length()];


for (int i = 0; i < inputString.length(); i++) {
tempArray[i] = inputString.charAt(i);
}


// Sort without considering the case
Arrays.sort(tempArray, new Comparator<Character>() {

// comparison of characters
public int compare(Character c1, Character c2)
{
return Character.compare(
Character.toLowerCase(c1),
Character.toLowerCase(c2));
}
});


// To transform a Character array to a String, use StringBuilder.
StringBuilder sb
= new StringBuilder(tempArray.length);


for (Character c : tempArray)
sb.append(c.charValue());


return sb.toString();
}



public static void main(String[] args)
{
// each input string
String inputString = "helloman";


// Sorting the input string and putting it in a string by calling method 1
String outputString = sortString(inputString);
// Input as well as output strings should be printed and displayed.
System.out.println("Input String : " + inputString);
System.out.println("Output String : "
+ outputString);
}
}

Output

aehllmno

Related Topics

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

4 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.