top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Sort a String In Java

Introduction

Sorting a string is a common task in programming, and Java provides powerful tools and techniques to accomplish this efficiently. Whether you need to arrange characters in ascending or descending order, Java's extensive library offers various methods and algorithms to sort strings easily. 

Sorting a string can be useful in a wide range of applications, from organizing data for efficient searching to solving complex algorithms.

Overview

In this tutorial, we will explore different ways to sort a string in Java, exploring the built-in methods provided by the Java standard library and custom implementations to understand the underlying principles better.

How To Sort a String in Java 8?

There are two main ways to sort a string in Java. We can either use the arrays.sort() method, or we can use Collections.sort() method. Let us explore both these methods.

Using the Arrays.sort() method

The Arrays.sort() method is a convenient way to sort an array in Java. It takes an array as input and sorts its elements in ascending order using the elements' natural order. This method directly modifies the original array, sorting its elements in place. It is a simple and efficient way to sort arrays of primitive types or objects that implement the Comparable interface.

Example:

import java.util.Arrays;

public class upGradTutorials {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Orange", "Banana", "Grape"};

        System.out.println("Before sorting:");
        System.out.println(Arrays.toString(fruits));

        Arrays.sort(fruits);

        System.out.println("After sorting:");
        System.out.println(Arrays.toString(fruits));
    }
}

Using the Collections.sort() method

The Collections.sort() method is used to sort a collection in Java. It takes a collection as input and sorts its elements in ascending order using the elements' natural order.

Unlike the Arrays.sort() method, which works directly on arrays, the Collections.sort() method applies to any type of collection, including lists, sets, and queues. It uses the Comparable interface to determine the order of the elements. This method modifies the original collection, sorting its elements in place. It provides a flexible way to sort collections of objects.

Example:

import java.util.ArrayList;
import java.util.Collections;

public class upGradTutorials {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Orange");
        fruits.add("Banana");
        fruits.add("Grape");

        System.out.println("Before sorting:");
        System.out.println(fruits);

        Collections.sort(fruits);

        System.out.println("After sorting:");
        System.out.println(fruits);
    }
}

Methods

3 important methods allow us to sort strings. Let us explore each of them with examples.

Method 1: Arrays.sort() Method

import java.util.Arrays;

public class upGradTutorials {
    public static void main(String[] args) {
        String[] YO = {"Aritra", "Manisha", "Sritama", "Supratik",  "Atriya"};

        System.out.println("Before sorting:");
        System.out.println(Arrays.toString(YO));

        Arrays.sort(YO);

        System.out.println("After sorting:");
        System.out.println(Arrays.toString(YO));
    }
}

First, the program initializes a string array named YO with five elements: "Aritra", "Manisha", "Sritama", "Supratik", and "Atriya".

Next, the program prints the elements of the YO array before sorting using System.out.println and Arrays.toString(). This allows us to see the initial order of the elements.

Then, the Arrays.sort() method is called, passing the YO array as an argument. This method sorts the elements of the array in ascending order based on their natural order, which is lexicographically for strings.

After sorting, the program prints the elements of the YO array again using System.out.println and Arrays.toString(). This time, the array will display the sorted elements, showing the result of the sorting operation.

Method 2: Using Java 8 Streams and sorted() Method

import java.util.Arrays;

public class upGradTutorials {
    public static void main(String[] args) {
        String[] Courses = {"Data Science", "Web Development", "Analytics", "Java"};

        System.out.println("Before sorting:");
        System.out.println(Arrays.toString(Courses));

        Arrays.stream(Courses)
                .sorted()
                .toArray(String[]::new);

        System.out.println("After sorting:");
        System.out.println(Arrays.toString(Courses));
    }
}

In this method, the program initializes a string array named Courses with four elements: "Data Science", "Web Development", "Analytics", and "Java". Before sorting, the program prints the elements of the Courses array using Arrays.toString() and System.out.println.

The Arrays.stream() method converts the Courses array into a stream of strings. Then, the sorted() method is applied to the stream to sort the elements in ascending order using the elements' natural order. However, it's important to note that this method does not assign the sorted elements back to the Courses array. Therefore, when the program prints the Courses array after sorting, it will display the original unsorted elements.

Method 3: reverseOrder() Method

import java.util.Arrays;
import java.util.Comparator;

public class upGradTutorials {
    public static void main(String[] args) {
        String[] YO = {"Aritra", "Manisha", "Sritama", "Supratik", "Atriya"};

        System.out.println("Before sorting:");
        System.out.println(Arrays.toString(YO));

        Arrays.sort(YO, Comparator.reverseOrder());

        System.out.println("After sorting:");
        System.out.println(Arrays.toString(YO));
    }
}

In this program, the Comparator.reverseOrder() method is used as the comparator to sort the elements of the YO array in descending order. First, the program initializes a string array named YO with five elements: "Aritra", "Manisha", "Sritama", "Supratik", and "Atriya".

Next, the program prints the elements of the YO array before sorting using System.out.println and Arrays.toString(). This allows us to see the initial order of the elements. The Arrays.sort() method is called, passing the array and the custom comparator as arguments. This results in sorting the elements in descending order based on their natural order. The program then prints the elements of the YO array before and after sorting to verify the sorting operation.

Java Sort String Alphabetically or In Ascending Order  

To sort string array in Java in alphabetical or ascending order, you can use the Arrays.sort() method from the Java standard library. This method provides a convenient way to sort an array in its natural order. Here's an example code snippet demonstrating how to sort a string array in ascending order:

import java.util.Arrays;

public class upGradTutorials {
    public static void main(String[] args) {
        String[] strings = {"apple", "banana", "cherry", "date"};

        System.out.println("Before sorting:");
        System.out.println(Arrays.toString(strings));

        Arrays.sort(strings);

        System.out.println("After sorting in ascending order:");
        System.out.println(Arrays.toString(strings));
    }
}

In this program, we have a string array strings containing four elements: "apple", "banana", "cherry", and "date". First, the program prints the elements of the strings array before sorting using System.out.println and Arrays.toString().

Then, the Arrays.sort() method is used to sort the elements of the array in ascending order. This method arranges the strings in lexicographic order, where "apple" comes before "banana", and so on. After sorting, the program prints the elements of the strings array again, this time displaying them in the sorted order.

How to Sort String in Descending Order Java or Reverse Natural Order  

To sort a string in Java in descending order or reverse natural order in Java, you can use the Arrays.sort() method and a custom Comparator. The Comparator interface allows you to define a custom comparison logic for sorting objects. 

Here's an example code snippet demonstrating how to sort a string array in descending order:

import java.util.Arrays;
import java.util.Collections;

public class upGradTutorials {
    public static void main(String[] args) {
        String[] strings = {"apple", "banana", "cherry", "date"};

        System.out.println("Before sorting:");
        System.out.println(Arrays.toString(strings));

        Arrays.sort(strings, Collections.reverseOrder());

        System.out.println("After sorting in descending order:");
        System.out.println(Arrays.toString(strings));
    }
}

In this program, we have the same string array strings as in the previous example. First, the program prints the elements of the strings array before sorting.

We use the Collections.reverseOrder() method to sort the array in descending order as the comparator for the Arrays.sort() method. This instructs the sort operation to arrange the strings in the reverse natural order, where "date" comes before "cherry", and so on.

After sorting, the program prints the elements of the strings array again, displaying them in descending order. Using the Arrays.sort() method with Collections.reverseOrder(), the program successfully sorts the strings in the array in descending or reverse natural order.

Conclusion 

Sorting a string in Java is a fundamental operation that programmers often encounter in various scenarios. By understanding these techniques, you now have the tools to manipulate and order strings according to your specific requirements efficiently. 

Sorting strings can be a powerful tool in data organization, search optimization, and algorithmic problem-solving. To enhance your programming skills and expand your ability to tackle diverse challenges, consider taking up a professional course offered by upGrad.

FAQs

  1. How to sort a string in Java using inbuilt function?

To sort a string in Java using an inbuilt function, you can utilize the Arrays.sort() method, passing in the string array as the argument, which will sort the elements in ascending order based on their natural order.

  1. How to sort a string in Java without using inbuilt function?

Without using an inbuilt function, you can implement a custom sorting algorithm, such as quicksort or insertion sort, to sort a string array in Java by comparing and rearranging the elements based on your desired sorting logic.

  1. How to sort strings in Python?

In Python, you can sort strings by using the sorted() function, which returns a new sorted list of strings, or by invoking the sort() method on a list of strings, which sorts the list in place, both by default in ascending order based on the strings' lexicographic order.

  1. What is the method for sorting a string in C++?

Sorting techniques in C++ include bubble, insertion, and quick sort. Hashing and using the inbuilt library function <algorithm> are other sorting methods in C++.

Leave a Reply

Your email address will not be published. Required fields are marked *