×

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

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a 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...

4 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

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

Can Abstract Classes have Static Methods in Java

Abstract Class An abstract class in Java is one that explicitly uses the keyword "abstract" in its declaration. There are options for both non-abstract and abstract techniques (method with the body)....

4 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

How to Convert Hexadecimal to Decimal in Java

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

2 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.