×

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

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 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 Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.