×

Sorting a String in Java

Sorting a String in Java

Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String objects can be used to check if two strings are composed of similar alphabets. In Java, there are several methods available for sorting strings.

How to sort a String in Java

Java provides the following ways to sort a string:

  1. Using for Loops

The basic logical programming approach for sorting anarray of elements is to use nested for loops. Inside the for loops we have used an if statement.Inside the if statement, we have compared the elements. If the condition returns true, it performs swapping and sort the elements, accordingly.

SortwLoop.java

 import java.util.*;
 public class SortwLoop
 {
     /* Driver Code */
      public static void main(String []args)
      {
         /* Unsorted order */
         String[] fruits = {"Grapes", "Banana", "Apple", "Jackfruit"}; 
         System.out.println("Before Sorting: "+(Arrays.toString(fruits)));
         /* Nested for loop to compare one string with another */
         for (int i = 0; i < fruits.length; i++)
         {
             for (int j = i + 1; j < fruits.length; j++)
             {
                 /* if condition to compare each element of String array with rest elements */
                 if (fruits[i].compareTo(fruits[j])>0)
                 {
                     /*Swapping strings */
                     String temp = fruits[i]; 
                     fruits[i] = fruits[j]; 
                     fruits[j] = temp; 
                 }
             }
         }
         /* Sorted order */
         System.out.println("After Sorting: "+(Arrays.toString(fruits)));
      }
 } 

Output:

 Before Sorting: [Grapes, Banana, Apple, Jackfruit]
 After Sorting: [Apple, Banana, Grapes, Jackfruit] 

In the above code snippet, the main()method consist an array of String objects fruits. The first for loop start with 0th element and compares it with rest of the elements of String array fruitsusing the inner for loop. After the first iteration of outer for loop is complete, first element gets its correct position and the loop continues until the condition becomes false.

  • Using Arrays.sort() Method

Arrays class belongs to java.util package. The class defines sort() method that performs sorting of an array in ascending order. Sorting using Arrays.sort() requires fewer lines of code.

SortwArraysort.java

 import java.util.*;
 public class SortwArraysort
 {
     /* Driver Code */
      public static void main(String []args)
      {
         /* Unsorted order */
         String[] cities = {"Mumbai", "Banglore", "Surat", "Delhi", "Chennai"}; 
         System.out.println("Before Sorting: "+(Arrays.toString(cities)));
         /* sort() method */
         Arrays.sort(cities);
         /*Sorted order */
         System.out.println("After Sorting: "+(Arrays.toString(cities)));
      }
 } 

Output:

 Before Sorting: [Mumbai, Banglore, Surat, Delhi, Chennai]
 After Sorting: [Banglore, Chennai, Delhi, Mumbai, Surat] 

Here, an array of String objects is declared i.e., cities. The Arrays.sort() method takes one argument cities. It is a static method,so we can call it directly by suing the class name. It does not return any value.

  • Using List.sort() Method

The Java List interface provides a sort() method. It can be used to sort a list of String objects. The following program demonstrates use of sort() method.

SortwListsort.java

 import java.util.*;
 public class SortwListsort
 {
     /* Driver Code */
     public static void main(String []args)
     {
         /* Unsorted list */
         List<String> color = Arrays.asList("Cyan", "Black", "Red", "Yellow", "Green");
         System.out.println("Before Sorting: "+color);
         System.out.println("After Sorting: ");
         /* Ascending Order */
         color.sort( Comparator.comparing( String::toString ) );
         System.out.println("1. Ascending order: "+color);
         /* Descending Order */
         color.sort( Comparator.comparing( String::toString ).reversed() );
         System.out.println("2. Descending order: "+color);
         }
 } 

Output:

 Before Sorting: [Cyan, Black, Red, Yellow, Green]
 After Sorting:
 1. Ascending order: [Black, Cyan, Green, Red, Yellow]
 2. Descending order: [Yellow, Red, Green, Cyan, Black] 

Here, the list of String objects color is in unsorted form. The sort() method arranges the objects into ascending and descending order.

  • Using Collections.sort() Method

The java.util.Collections package defines a sort() method that is similar to the Arrays.sort() method. But it has an advantage, Collections.sort() method can sort elements of Array and also other data structures like queue, linked list, etc.

SortwCollection.java

 import java.util.*;
 public class SortwCollection
 {
     /* Driver Code */
      public static void main(String []args)
      {    
         /* Unsorted list of Strings */
         List<String> fruits = Arrays.asList("Grapes", "Banana", "Apple", "Jackfruit"); 
         /* Ascending order */
         Collections.sort(fruits);
         System.out.println("Ascending order: "+fruits);
         /* Descending order */
         Collections.sort(fruits, Collections.reverseOrder());   
         System.out.println("Descending order: "+fruits);   
      }
 } 

Output:

 Ascending order: [Apple, Banana, Grapes, Jackfruit]
 Descending order: [Jackfruit, Grapes, Banana, Apple] 

Here, the list of String objects fruits is in unsorted form. The Collections.sort() method arranges the objects into ascending order and Collections.reverseOrder()  method into descending order.

  • Using Java Stream (available in Java 8)

In Java 8, the Stream API is available. Stream API provides a way to sort String objects using ASCII values of the alphabets.

SortwStream.java

 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 public class SortwStream
 {
     /* Driver Code */
     public static void main(String[] args)
     {
         /* Unsorted string */
         String str = "CADB";
          System.out.println("Unsorted String: "+str);
         /* Sorting operation */
         str = Stream.of(str.split("")).sorted().collect(Collectors.joining());
         /* Sorted String */
         System.out.println("Sorted String: "+str);
     }
 } 

Output:

 Unsorted String: CADB
 Sorted String: ABCD 

Here, the String stris declared. The Stream API, first splits the string and then performs sorting according to the ASCII values.

This article discusses various methods available in Java, for sorting an array of String with examples.


Related Topics

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.