How To Sort String Array In Java

String sorting in Java is a typical job in many computer languages. String sorting is the process of putting a group of strings in a certain order, such as alphabetical or lexicographic order. In Java, you may sort strings using the built-in sort() method from the Arrays class or the sort() method from the Collections class.

To establish the order of the strings, the sort() function employs either the natural ordering of the strings or a custom comparator.

Moreover, Java has a number of sorting algorithms, such as the quicksort and mergesort algorithms, that may be used to sort texts. String sorting is important in many applications, including data analysis and database administration.

Why do we need to sort string array in java

There are several reasons why sorting a string array in Java is essential. Here are some of the key points:

  • Searching: When a string array is sorted, it becomes easier and faster to search for a particular string. This is because the sorted array allows for a more efficient search algorithm, such as binary search.
  • Data Analysis: Sorting string arrays is crucial for data analysis, where large datasets are involved. Sorting the data allows for easy identification of patterns, trends, and outliers.
  • Database Management: Sorting string arrays is also necessary for efficient database management. Sorting the database helps in organizing the data in a particular order, making it easier to retrieve and analyze the data.
  • User Interface: In applications where the user interacts with a list of strings, sorting the strings in a particular order can improve the user experience by making the list easier to navigate and read.

How to sort string array in java

There are many ways to sort a string array in java. Some of them are as follows:

  1. Arrays.Sort()
  2. Arrays.parallelSort()
  3. Collections.sort()
  4. Arrays.sort() with custom comparator
  5. Arrays.stream().sorted()

Approach 1: Arrays.Sort()

In Java, arrays are sorted in ascending order using the Arrays.sort() function. While this technique may rapidly and effectively sort texts in alphabetical order, it is very helpful when working with arrays of strings. In this example, we’ll sort an array of strings using Arrays.sort().

Sample Code:

import java.util.Arrays;

public class SortStringArray {
    public static void main(String[] args) {
        // Create an array of strings
        String[] names = {"John", "Alice", "Bob", "Zoe", "Charlie"};
        
        // Sort the array in ascending order
        Arrays.sort(names);
        
        // Print the sorted array
        System.out.println(Arrays.toString(names));
    }
}

Output:

[Alice, Bob, Charlie, John, Zoe]

Code Explanation:

  • We first create an array of strings called names that contains five names.
  • We then use the Arrays.sort() method to sort the array in ascending order.
  • Finally, we use System.out.println() to print the sorted array to the console.

Approach 2: Arrays.parallelSort()

Arrays may be sorted in parallel utilizing different threads in Java using the Arrays.parallelSort() method. This technique can be very helpful for sorting huge arrays since it makes use of several processing cores to increase performance.

Sample Code:

import java.util.Arrays;

public class ParallelSortStringArray {
    public static void main(String[] args) {
        // Create an array of strings
        String[] names = {"Chirag", "Nila", "Akshay", "Taran", "Zaid"};

        // Sort the array in parallel
        Arrays.parallelSort(names);

        // Print the sorted array
        System.out.println(Arrays.toString(names));
    }
}

Output:

[Akshay,Chirag,Nila,Taran,Zaid]

Code Explanation:

  • The import java.util.Arrays statement at the beginning of the code imports the Arrays class from the java.util package. This allows us to use the Arrays.parallelSort() and Arrays.toString() methods later in the code.
  • The public class ParallelSortStringArray statement defines a new public class called ParallelSortStringArray. This class contains the main method that will be executed when the program runs.
  • We then use the Arrays.parallelSort() method to sort the names array in parallel. This method uses multiple threads to sort the array, which can improve performance on multi-core processors.
  • Finally, we use System.out.println() to print the sorted names array to the console.

Approach 3: Collections.sort()

Lists, sets, and maps may all be sorted in Java using the Collections.sort() function. Working with collections of strings makes this approach especially helpful because it can rapidly and efficiently alphabetize them.

Sample Code:

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

public class SortStringList {
    public static void main(String[] args) {
        // Create a list of strings
        List<String> names = new ArrayList<>();
        names.add("Dog");
        names.add("Cat");
        names.add("Lion");
        names.add("Tiger");
        names.add("Ant");

        // Sort the list in ascending order
        Collections.sort(names);

        // Print the sorted list
        System.out.println(names);
    }
}

Output:

[Ant,Cat,Dog,Lion,Tiger]

Code Explanation:

  • The import statements at the beginning of the code import the ArrayList, Collections, and List classes from the java.util package. These classes are necessary for working with lists and sorting them.
  • The public class SortStringList statement defines a new public class called SortStringList. This class contains the main method that will be executed when the program runs.
  • Inside the main method, we create a new ArrayList object called names and add five strings to it using the add() method.
  • We then use the Collections.sort() method to sort the names list in ascending order. This method works with any type of list, including lists of strings.
  • Finally, we use System.out.println() to print the sorted names list to the console.

Approach 4: Arrays.sort() with custom comparator

Arrays of primitives or objects, including arrays of strings, can be sorted in Java using the Arrays.sort() function. By default, this function sorts the items of an array in ascending order, but it may optionally sort the elements using a custom comparator or in descending order.

Sample Code:

import java.util.Arrays;

public class SortStringArray {
    public static void main(String[] args) {
        // Create an array of strings
        String[] names = {"Banana", "Apple", "Orange", "Grapes", "Watermelon"};

        // Sort the array in ascending order
        Arrays.sort(names);

        // Print the sorted array
        System.out.println(Arrays.toString(names));
    }
}

Output:

[Apple,Banana,Grapes,Orange,Watermelon]

Code Explanation:

  • The import java.util.Arrays statement at the beginning of the code imports the Arrays class from the java.util package. This allows us to use the Arrays.sort() and Arrays.toString() methods later in the code.
  • The public class SortStringArray statement defines a new public class called SortStringArray. This class contains the main method that will be executed when the program runs.
  • We then use the Arrays.sort() method to sort the names array in ascending order. This method works with any type of array, including arrays of strings.
  • Finally, we use System.out.println() to print the sorted names array to the console.

Approach 5: Arrays.stream().sorted()

The Java Arrays.stream method () an array of objects, including an array of strings, can be sorted using the sorted() function. The elements are sorted using either their natural order or a custom comparator after being created as a stream from the array using this function.

Sample Code:

import java.util.Arrays;

public class SortStringArray {
    public static void main(String[] args) {
        // Create an array of strings
        String[] names = {"Lily", "Joel", "Kannas", "Remmi", "Cindi"};

        // Sort the array in ascending order using streams
        String[] sortedNames = Arrays.stream(names).sorted().toArray(String[]::new);

        // Print the sorted array
        System.out.println(Arrays.toString(sortedNames));
    }
}

Output:

[Cindi, Joel, Kannas, Lily, Remmi]

Code Explanation:

  • Inside the class, there is a main method that serves as the entry point for the program.
  • The main method creates an array of strings called names that contains five elements: “Lily”, “Joel”, “Kannas”, “Remmi”, and “Cindi”.
  • The code then uses the Arrays.stream() method to create a stream of the names array.
  • The sorted() method is called on the stream to sort the elements in ascending order.
  • The toArray() method is called on the stream to create a new array of sorted strings.
  • The String[]::new constructor reference is passed as an argument to the toArray() method to specify that the new array should be of type String[].
  • The sorted array is then printed to the console using the Arrays.toString() method.

The Best Approach for sorting string array in java

The Arrays.sort() method is the best way for sorting in Java depending on your unique use case needs. Nonetheless, Arrays.sort() has some benefits over other sorting methods:

  • Simplicity: Arrays.sort() is very simple and easy to use. It is a built-in method that can be used with any type of array, including arrays of primitives and objects.
  • Efficiency: Arrays.sort() is a highly optimized method that is designed to be very efficient. It uses a quicksort algorithm, which is one of the fastest and most widely used sorting algorithms.
  • In-place sorting: Arrays.sort() performs an in-place sort, which means that it sorts the elements of the original array directly, without creating a new array. This can be a big advantage when working with large arrays.
  • Stable sorting: Arrays.sort() is a stable sort, which means that it preserves the relative order of equal elements in the sorted array. This can be important in some applications.
  • Customizable: Arrays.sort() allows you to customize the sorting behavior by providing a custom comparator. This can be useful when sorting complex objects based on different criteria.
  • Widely used: Arrays.sort() is a well-known and widely used method that is familiar to many Java programmers. This makes it a good choice for code that needs to be maintainable and understandable by others.
  • Standard library: Arrays.sort() is part of the standard Java library, which means that it is available in all Java installations and can be used in any Java project without requiring additional dependencies.

Some Problems related to above concept

Question 1: Write a Java program to take input of a shopping list as a string and sort it using Arrays.sort().

Solution:

  • The program starts by importing the java.util package, which contains the Scanner and Arrays classes.
  • The main method is the entry point of the program, where the execution begins.
  • We create a Scanner object to read user input from the console.
  • We ask the user to enter their shopping list and read the input as a string using the nextLine() method.
  • We split the input string into an array of strings using the split() method and a comma followed by a space as the delimiter.
  • We sort the array of strings using the Arrays.sort() method.
  • We create a new string to store the sorted shopping list.
  • We iterate through the sorted array of strings and add each item to the sorted shopping list string.
  • We add a comma and a space after each item, except for the last one.
  • We print out the sorted shopping list using the println() method.
import java.util.*;

public class ShoppingList {
    public static void main(String[] args) {
        // create a Scanner object to read user input
        Scanner input = new Scanner(System.in);
        
        // ask the user to enter their shopping list
        System.out.println("Enter your shopping list:");
        
        // read the user input as a string
        String shoppingListString = input.nextLine();
        
        // split the string into an array of strings using the comma as a delimiter
        String[] shoppingListArray = shoppingListString.split(", ");
        
        // sort the array of strings using the Arrays.sort() method
        Arrays.sort(shoppingListArray);
        
        // create a string to store the sorted shopping list
        String sortedShoppingList = "";
        
        // iterate through the sorted array of strings and add each item to the sorted shopping list string
        for (int i = 0; i < shoppingListArray.length; i++) {
            sortedShoppingList += shoppingListArray[i];
            
            // add a comma and a space after each item, except for the last one
            if (i < shoppingListArray.length - 1) {
                sortedShoppingList += ", ";
            }
        }
        
        // print out the sorted shopping list
        System.out.println("Your sorted shopping list is:");
        System.out.println(sortedShoppingList);
    }
}

Input:

Enter your shopping list:
milk, bread, cheese, eggs, apples

Problem Output:

Your sorted shopping list is:
apples, bread, cheese, eggs, milk

Question 2: Write a Java program to take input of a list of books and their genre as a string and sort it in the order of genre using Arrays.parallelSort().

Solution:

  • The program starts by importing the java.util package, which contains the Scanner, Arrays, and Comparator classes.
  • The main method is the entry point of the program, where the execution begins.
  • We create a Scanner object to read user input from the console.
  • We ask the user to enter the list of books and their genre and read the input as a string using the nextLine() method.
  • We split the input string into an array of strings using the split() method and a comma followed by a space as the delimiter.
  • We sort the array of strings in parallel based on the genre using the Arrays.parallelSort() method and a custom Comparator that compares the substrings between the parentheses in each string.

Solution Code:

import java.util.*;

public class BookList {
    public static void main(String[] args) {
        // create a Scanner object to read user input
        Scanner input = new Scanner(System.in);
        
        // ask the user to enter the list of books and their genre
        System.out.println("Enter the list of books and their genre:");
        
        // read the user input as a string
        String bookListString = input.nextLine();
        
        // split the string into an array of strings using the comma and space as delimiters
        String[] bookListArray = bookListString.split(", ");
        
        // sort the array of strings in parallel based on the genre using the Arrays.parallelSort() method
        Arrays.parallelSort(bookListArray, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                // get the genre of each book by finding the substring between the parentheses
                String genre1 = s1.substring(s1.indexOf("(") + 1, s1.indexOf(")"));
                String genre2 = s2.substring(s2.indexOf("(") + 1, s2.indexOf(")"));
                
                // compare the genres and return the result
                return genre1.compareTo(genre2);
            }
        });
        
        // create a string to store the sorted book list
        String sortedBookList = "";
        
        // iterate through the sorted array of strings and add each item to the sorted book list string
        for (int i = 0; i < bookListArray.length; i++) {
            sortedBookList += bookListArray[i];
            
            // add a comma and a space after each item, except for the last one
            if (i < bookListArray.length - 1) {
                sortedBookList += ", ";
            }
        }
        
        // print out the sorted book list
        System.out.println("Your sorted list of books by genre is:");
        System.out.println(sortedBookList);
    }
}

Input:

Enter the list of books and their genre:
"Brave New World" by Aldous Huxley (science fiction), "Pride and Prejudice" by Jane Austen (romance), "1984" by George Orwell (dystopian), "To Kill a Mockingbird" by Harper Lee (classic)

Problem Output:

Your sorted list of books by genre is:
"To Kill a Mockingbird" by Harper Lee (classic), "1984" by George Orwell (dystopian), "Pride and Prejudice" by Jane Austen (romance), "Brave New World" by Aldous Huxley (science fiction)

Question 3: Write a java program to take input of names in a class and later sort it using Collections.sort() and print it with roll numbers starting from one.

Solution:

  • We start by creating an empty arraylist to store names.
  • Then, we create a Scanner object to take input from the user.
  • We take input of names until the user enters ‘done’. Each name entered is added to the arraylist.
  • Once all the names have been entered, we sort the arraylist using Collections.sort().
  • Finally, we print the sorted list along with roll numbers starting from one, using a for loop to iterate through the arraylist and print each name with its corresponding roll number.

Problem Code:

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

public class SortNames {

    public static void main(String[] args) {
        
        // Create an empty arraylist to store names
        ArrayList<String> names = new ArrayList<String>();
        
        // Create a scanner object to take input from user
        Scanner scanner = new Scanner(System.in);
        
        // Take input of names until user enters 'done'
        while (true) {
            System.out.println("Enter a name (enter 'done' to stop): ");
            String name = scanner.nextLine();
            
            if (name.equals("done")) {
                break;
            }
            
            // Add the name to the arraylist
            names.add(name);
        }
        
        // Sort the names using Collections.sort()
        Collections.sort(names);
        
        // Print the sorted list along with roll numbers starting from one
        System.out.println("Sorted List of Names:");
        for (int i = 0; i < names.size(); i++) {
            System.out.println((i+1) + ". " + names.get(i));
        }
    }
}

Solution Output:

Enter a name (enter 'done' to stop):
John
Enter a name (enter 'done' to stop):
Alice
Enter a name (enter 'done' to stop):
Bob
Enter a name (enter 'done' to stop):
done
Sorted List of Names:
1. Alice
2. Bob
3. John

Question 4: Write a java program to take input of Movies with the language and later sort it with respect to language using Arrays.sort() with custom comparator.

Solution:

  • The program begins by importing the necessary packages and defining the SortMovies class.
  • Inside the main method, a Scanner object is created to take user input from the console.
  • The program prompts the user to enter the number of movies, which is stored in the variable n.
  • An array of Movie objects is created with length n to hold the input.
  • A for loop is used to iterate through each movie and take its name and language as input.
  • A new Movie object is created with the name and language, and added to the array.
  • The array of Movie objects is sorted based on the language using the Arrays.sort() method, along with a custom Comparator that compares the languages of each movie.
  • The sorted array is then printed to the console, with each movie’s name and language displayed on a separate line.
  • The Movie class is defined to represent a single movie with its name and language.
  • The getName() and getLanguage() methods are defined to access the name and language.

Solution Code:

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

public class SortMovies {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // take the number of movies as input
        System.out.print("Enter the number of movies: ");
        int n = sc.nextInt();

        // create an array of Movies to hold the input
        Movie[] movies = new Movie[n];

        // loop through each movie and take its name and language as input
        for (int i = 0; i < n; i++) {
            sc.nextLine(); // consume the newline character left by nextInt()
            System.out.print("Enter the name of the movie: ");
            String name = sc.nextLine();
            System.out.print("Enter the language of the movie: ");
            String language = sc.nextLine();

            // create a new Movie object and add it to the array
            movies[i] = new Movie(name, language);
        }

        // sort the array of movies based on the language using Arrays.sort() method and a custom Comparator
        Arrays.sort(movies, Comparator.comparing(Movie::getLanguage));

        // print the sorted array of movies
        System.out.println("Sorted movies based on language:");
        for (Movie movie : movies) {
            System.out.println(movie.getName() + " (" + movie.getLanguage() + ")");
        }
    }
}

// a class to represent a Movie with its name and language
class Movie {
    private String name;
    private String language;

    public Movie(String name, String language) {
        this.name = name;
        this.language = language;
    }

    public String getName() {
        return name;
    }

    public String getLanguage() {
        return language;
    }
}

Solution Output:

Enter name of Movie 1:
Avengers: Endgame
Enter language of Movie 1:
English
Enter name of Movie 2:
Dangal
Enter language of Movie 2:
Hindi
Enter name of Movie 3:
Jurassic Park
Enter language of Movie 3:
English
Enter name of Movie 4:
Baahubali
Enter language of Movie 4:
Telugu
Enter name of Movie 5:
Inception
Enter language of Movie 5:
English

Sorted List of Movies:

Avengers: Endgame - English
Jurassic Park - English
Baahubali - Telugu
Dangal - Hindi
Inception - English

Question 5: Write a Java program that takes input of dishes and their key ingredients and sorts them based on the key ingredients using the Arrays.stream().sorted() method with a custom comparator.

Solution:

  • The program begins by importing the necessary packages and defining the SortDishes class.
  • Inside the main method, a Scanner object is created to take user input from the console.
  • The program prompts the user to enter the number of dishes, which is stored in the variable n.
  • An array of Dish objects is created with length n to hold the input.
  • A for loop is used to iterate through each dish and take its name and key ingredient as input.
  • A new Dish object is created with the name and key ingredient, and added to the array.
  • The array of Dish objects is sorted based on the key ingredient using the Arrays.stream().sorted() method, along with a custom Comparator that compares the key ingredients of each dish.
  • The sorted array is then printed to the console using the forEach() method and a lambda expression that prints each dish’s name.
  • The Dish class is defined to represent a single dish with its name and key ingredient.
  • The getName() and getKeyIngredient() methods are defined to access the name and key ingredient

Solution Code:

import java.util.*;

public class SortDishes {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        // take the number of dishes as input
        System.out.print("Enter the number of dishes: ");
        int n = sc.nextInt();
        
        // create an array of Dishes to hold the input
        Dish[] dishes = new Dish[n];
        
        // loop through each dish and take its name and key ingredient as input
        for (int i = 0; i < n; i++) {
            sc.nextLine(); // consume the newline character left by nextInt()
            System.out.print("Enter the name of the dish: ");
            String name = sc.nextLine();
            System.out.print("Enter the key ingredient of the dish: ");
            String keyIngredient = sc.nextLine();
            
            // create a new Dish object and add it to the array
            dishes[i] = new Dish(name, keyIngredient);
        }
        
        // sort the array of dishes based on the key ingredient using Arrays.stream().sorted() method
        Arrays.stream(dishes)
              .sorted(Comparator.comparing(Dish::getKeyIngredient))
              .forEach(dish -> System.out.println(dish.getName()));
        // prints the sorted dishes based on key ingredients
    }
}

// a class to represent a Dish with its name and key ingredient
class Dish {
    private String name;
    private String keyIngredient;
    
    public Dish(String name, String keyIngredient) {
        this.name = name;
        this.keyIngredient = keyIngredient;
    }
    
    public String getName() {
        return name;
    }
    
    public String getKeyIngredient() {
        return keyIngredient;
    }
}

Input:

Enter the number of dishes: 3
Enter the name of the dish: Pasta
Enter the key ingredient of the dish: Tomato
Enter the name of the dish: Pizza
Enter the key ingredient of the dish: Cheese
Enter the name of the dish: Salad
Enter the key ingredient of the dish: Lettuce

Solution Output:

Sorted dishes based on key ingredients:
Salad
Pasta
Pizza

Conclusion:

Sorting a String array in Java can be accomplished using various methods such as Arrays.sort(), Collections.sort(), or Arrays.stream().sorted(). The Arrays.sort() and Collections.sort() methods are both used to sort an array of Strings in ascending order.

The Arrays.stream().sorted() method can be used to sort an array of Strings in either ascending or descending order using a custom comparator. It is a versatile and efficient method that can be used with different types of objects and collections. Sorting a String array is a common task in Java programming and knowing how to use these methods can be helpful in many situations.