Java program to sort names in an alphabetical order

Let’s learn java program to sort names in an alphabetical order.

Java program to sort names in an alphabetical order

Sort names in alphabetical order is one of the common java interview question. Now let’s learn to sort names alphabetically.

  • In java sort names alphabetically first user enters number of strings in arranging strings in an alphabetical order.
  • In the next step number of strings is stored in integer variable ‘number’ using nextInt() method Scanner class.
  • Then for loop is used to store all the strings entered by user. Finally compare first letter of each string to store in alphabetical order.

Also read – nested classes in java

Here’s how to sort names alphabetically in java or java program to sort a given list of names in ascending order,

import java.util.Scanner;
public class SortStringArray 
{
   public static void main(String[] args)
   {
      int number;
      String str;
      Scanner sc1 = new Scanner(System.in);
      System.out.print("Please enter number of strings : ");
      number = sc1.nextInt();
      String[] players = new String[number];
      Scanner sc2 = new Scanner(System.in);
      System.out.println("Enter all strings : ");
      for(int a = 0; a < number; a++)
      {
         players[a] = sc2.nextLine();
      }
      for(int a = 0; a < number; a++)
      {
         for(int b = a + 1; b < number; b++)
         {
            // java alphabetical sort
            if(players[a].compareTo(players[b]) > 0) 
            {
               str = players[a];
               players[a] = players[b];
               players[b] = str;
            }
         }
      }
      System.out.print("In sorted order : ");
      for(int a = 0; a < number - 1; a++) 
      {
         System.out.print(players[a] + ", ");
      }
      System.out.print(players[number - 1]);
      sc1.close();
      sc2.close();
   }
}



Output:

java program to sort names in an alphabetical order

Arrange sentence in alphabetical order in java

We can use collection to arrange sentence in alphabetical order in java.

import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class ArrangeInAlphabeticalOrder 
{
   public static void main(String[] args) 
   {
      Set set = new TreeSet();
      String strInput = "hi all welcome to flower brackets blog";
      System.out.println("Before - arrange sentence in alphabetical order: " + strInput);
      StringTokenizer strToken = new StringTokenizer(strInput," ");
      while(strToken.hasMoreElements())
      {
         set.add(strToken.nextElement());
      }
      System.out.println("After - arrange sentence in alphabetical order: " + set);
   }
}


Output:

Before – arrange sentence in alphabetical order: hi all welcome to flower brackets blog
After – arrange sentence in alphabetical order: [all, blog, brackets, flower, hi, to, welcome]


Sort array of strings in java

Let’s learn to sort array of strings in java. To sort array of strings compare each and every string of given string array to remaining strings.

Now after comparing strings if output is greater than zero then swap the strings. Lastly print the output on the console.

Here’s the java program to sort array of strings,

import java.util.Arrays;

public class SortArrayOfStrings 
{
   public static void main(String[] args) 
   {
      String[] strFruits = {"Jackfruit", "Hazelnut", "Orange", "Apple", "Banana", "Nectarine"};
      int arrSize = strFruits.length;
      for(int a = 0; a < arrSize - 1; a++)
      {
         for(int b = a + 1; b < strFruits.length; b++)
         {
            if(strFruits[a].compareTo(strFruits[b]) > 0)
            {
               String strTemp = strFruits[a];
               strFruits[a] = strFruits[b];
               strFruits[b] = strTemp;
            }
         }
      }
      System.out.println(Arrays.toString(strFruits));
   }
}


Output:

[Apple, Banana, Hazelnut, Jackfruit, Nectarine, Orange]


Write a program which will read a string and rewrite it in the alphabetical order in java

Let’s learn to write a program which will read a string and rewrite it in the alphabetical order in java.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class JavaAlphabeticalOrder 
{
   String rewriteOrder(String strInput)
   {
      char[] ch = strInput.toCharArray();
      Arrays.sort(ch);
      String str = new String(ch);
      return str;
   }

   public static void main(String[] args) throws IOException 
   {
      System.out.println("Please enter a string rewrite it in the alphabetical order: ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String str = br.readLine();
      JavaAlphabeticalOrder obj = new JavaAlphabeticalOrder();
      String strAlphabetical = obj.rewriteOrder(str);
      System.out.println("String in alphabetic order in java: " + strAlphabetical);
   }
}


Output:

Please enter a string rewrite it in the alphabetical order: hi all welcome to flower brackets blog
String in alphabetic order in java: aabbcceeeefghiklllllmoooorrsttww


How to check if a string is in alphabetical order in java

To check if a string is in alphabetical order or not first store the given string in character array ‘chArray’.

Now this character array is sorted using Arrays.sort() method. In the next step check if characters in sorted array are same as given string.

If they are same then print given string is in alphabetical order else print given string is not in alphabetical order on console.

import java.util.Arrays;

public class CheckStringIfAlphabetical 
{
   public static void main(String[] args) 
   {
      String strInput = "hello world java";
      if(checkIfAlphabaticOrder(strInput))
      {
         System.out.println("Given string is in alphabetical order.");
      }
      else
      {
         System.out.println("Given string is not in alphabetical order.");
      }
   }

   static boolean checkIfAlphabaticOrder(String str)  
   {  
      int size = str.length();  
      char[] chArray = new char[size];  
      for(int a = 0; a < size; a++) 
      {  
         chArray[a] = str.charAt(a);  
      }  
      Arrays.sort(chArray);
      for(int a = 0; a < size; a++)
      {
         if(chArray[a] != str.charAt(a))
         {
            return false;
         }
      }                
      return true;      
   }
}


Output:

Given string is not in alphabetical order.


Sort string in descending order java

import java.util.Arrays;

public class SortStringInDescendingOrder 
{
   static void descendingOrder(char[] ch)  
   { 
      Arrays.sort(ch); 
      stringDescending(ch);
   } 

   static void stringDescending(char[] chArray)  
   { 
      int a, size = chArray.length; 
      char temp; 
      for(a = 0; a < size / 2; a++)  
      { 
         temp = chArray[a]; 
         chArray[a] = chArray[size - a - 1]; 
         chArray[size - a - 1] = temp; 
      } 
   } 

   public static void main(String[] args) 
   {
      char[] chInput = "flowerbrackets".toCharArray(); 
      descendingOrder(chInput); 
      System.out.println(String.valueOf(chInput));
   }
}


Output:

wtsrrolkfeecba