×

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

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

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...

4 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 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.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Types of Sockets in Java

The fundamental idea behind Java's networking capability is the socket. Early in the 1980s, the Berkeley UNIX 4.2BSD version included the socket paradigm. Berkeley socket is the term employed as...

9 minutes read.