Alphabet sorting in java

Java Program to Sort Strings in an Alphabetical Order

In this java tutorial, we will learn how to sort Strings in an Alphabetical Order.

Java Example: Arranging Strings in an Alphabetical Order

In this program, we are asking user to enter the count of strings that he would like to enter for sorting. Once the count is captured using Scanner class, we have initialized a String array of the input count size and then are running a for loop to capture all the strings input by user.

Once we have all the strings stored in the string array, we are comparing the alphabets starting from the first alphabet of each string to get them sorted in the alphabetical order.

import java.util.Scanner; public class JavaExample < public static void main(String[] args) < int count; String temp; Scanner scan = new Scanner(System.in); //User will be asked to enter the count of strings System.out.print("Enter number of strings you would like to enter:"); count = scan.nextInt(); String str[] = new String[count]; Scanner scan2 = new Scanner(System.in); //User is entering the strings and they are stored in an array System.out.println("Enter the Strings one by one:"); for(int i = 0; i < count; i++) < str[i] = scan2.nextLine(); >scan.close(); scan2.close(); //Sorting the strings for (int i = 0; i < count; i++) < for (int j = i + 1; j < count; j++) < if (str[i].compareTo(str[j])>0) < temp = str[i]; str[i] = str[j]; str[j] = temp; >> > //Displaying the strings after sorting them based on alphabetical order System.out.print("Strings in Sorted Order:"); for (int i = 0; i > >

Java Program to Sort Strings in an Alphabetical Order

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Hello Chaitanya, the “Arranging Strings in an Alphabetical Order” program doesn’t treats the issue extensively by comparing the 2 strings with each other, isn’t it? Otherwise what is the compareTo method then for? Thank you for our answer,
Hilda

Источник

Java – Sorting a String Array in Alphabetical Order

Learn to arrange an array of strings alphabetically using Stream.sorted() and Arrays.sort() methods. Also, learn to reverse sort using Comparator.reverseOrder() .

Java 8 stream APIs have introduced a lot of exciting features to write code in very precise ways which are more readable.

This example sorts the string array in a single line code using Stream . It uses the Stream.sorted() method which helps in sorting a stream of objects in their natural order or according to the provided Comparator.

For reverse sorting the array, use Comparator.reverseOrder() .

// Unsorted string array String[] strArray = < "Alex", "Charles", "Dean", "Amanda", "Brian" >; // Sorting the strings strArray = Stream.of(strArray) .sorted() .toArray(String[]::new); // Sorted array System.out.println("Sorted : " + Arrays.toString(strArray)); // Reverse sorting example strArray = Stream.of(strArray) .sorted(Comparator.reverseOrder()) .toArray(String[]::new); // Reverse Sorted array System.out.println("Sorted : " + Arrays.toString(strArray));
Sorted : [Alex, Amanda, Brian, Charles, Dean] Reverse Sorted : [Dean, Charles, Brian, Amanda, Alex]

Arrays.sort() provides similar functionality as Stream.sorted() if you are still in Java 7.

// Unsorted string array String[] strArray = < "Alex", "Charles", "Dean", "Amanda", "Brian" >; // Sorting the strings Arrays.sort(strArray); // Sorted array System.out.println("Sorted : " + Arrays.toString(strArray)); Arrays.sort(strArray, Comparator.reverseOrder()); // Reverse Sorted array System.out.println("Sorted : " + Arrays.toString(strArray));
Sorted : [Alex, Amanda, Brian, Charles, Dean] Reverse Sorted : [Dean, Charles, Brian, Amanda, Alex]

Drop me your questions related to comparing and sorting a string array in alphabetical order.

Читайте также:  Docker поменять версию php

Источник

Java Program To Sort an Array in Alphabetical Order

In this tutorial, we will learn how to sort the elements of an array in alphabetical order. Sorting refers to arranging data in order either alphabetically or numerically. But before moving forward, if you are not familiar with the concepts of the array, then do check the article Arrays in Java.

Input: a n m w r t s p

Output: a m n p r s t w

The above problem can be solved in the following ways:

Approach 1: Using compareTo()

Approach 2: Using Arrays.sort()

Approach 3: Using reverseOrder()

Let us look at each of these methods separately.

Program 1: Sort an Array in Alphabetical Order

In this approach, we will sort an array in alphabetical order by comparing each element with the rest elements.

Algorithm

  1. Start
  2. Declare an Array
  3. Initialize the Array
  4. Use two for loops to sort the array in alphabetical order.
  5. Use the first for loop to hold the elements.
  6. Use the second for loop to compare with the remaining elements.
  7. Use the compareTo() to compare.
  8. Swap the array elements.
  9. Print the updated array.
  10. Stop

Below is the code for the same.

The below program demonstrates how to sort an Array in Alphabetical Order by using compareTo() method.

//Java Program to sort an array in alphabetical order. import java.util.Arrays; import java.util.Scanner; public class Main < public static void main(String args[]) < Scanner sc=new Scanner(System.in); int n; //Declare the array size System.out.println("Enter the number of elements "); n=sc.nextInt(); //Initialize the array size String fruits[]=new String[n]; //Declare the array System.out.println("Enter the String "); Scanner sc1=new Scanner(System.in); for(int i=0; i//logic for sorting for(int i = 0; i0) < //swapping array elements String temp = fruits[i]; fruits[i] = fruits[j]; fruits[j] = temp; >> > //prints the sorted array in alphabetical order System.out.println(Arrays.toString(fruits)); > > 

Enter the number of array elements: 10
Enter the array elements:
Apple
Custard Apple
Banana
Kiwi
Guava
Orange
Papaya
Blackberry
Dates
Grapes
[Apple, Banana, Blackberry, Custard apple, Dates, Grapes, Guava, Kiwi, Orange, Papaya , ]

Program 2: Sort an Array in Alphabetical Order

In this approach, we will sort an array in alphabetical order using Arrays.sort() method.

Algorithm

  1. Start
  2. Declare an Array
  3. Initialize the Array
  4. Call the Arrays.sort() function to sort the array in alphabetical order.
  5. Print the sorted array.
  6. Stop.

Below is the code for the same.

The below program demonstrates how to sort an Array in Alphabetical Order by using Arrays.sort() method.

//Java Program to sort an array in alphabetical order. import java.util.Arrays; import java.util.Scanner; public class Main < public static void main(String args[]) < Scanner sc=new Scanner(System.in); Scanner sc1=new Scanner(System.in); int n; //Declare array size System.out.println("Enter the number of elements "); n=sc.nextInt(); //Initialize array size String str[]=new String[n]; //Declare array System.out.println("Enter the String "); for(int i=0; iArrays.sort(str); //Sort the array in alphabetical order System.out.println(Arrays.toString(str)); //Display the array > > 

Enter the number of elements
5
Enter the String
france
india
china
germany
italy
[china, france, germany, india, italy]

Program 3: Sort an Array in Alphabetical Order

In this approach, we will sort an array in alphabetical order using Arrays.sort() and then again sort it in reverse order using reverseOrder() method.

Algorithm

  1. Start
  2. Declare an Array
  3. Initialize the Array
  4. Call the Arrays.sort() function to sort the array in alphabetical order.
  5. Then call the reverseOrder() to sort the array in reverse order.
  6. Print the sorted array.
  7. Stop.
Читайте также:  Java list string convert to string array

Below is the code for the same.

Explanation: The below program demonstrates how to sort an Array in reverse Alphabetical Order using reverseOrder() method.

/*Java Program to sort an array alphabetically in reverse order*/ import java.util.Arrays; import java.util.Scanner; import java.util.*; public class Main < public static void main(String args[]) < Scanner sc=new Scanner(System.in); Scanner sc1=new Scanner(System.in); int n; //Declare array size System.out.println("Enter the number of elements "); n=sc.nextInt(); //Initialize array size String str[]=new String[n]; //Declare array System.out.println("Enter the String "); for(int i=0; iArrays.sort(str,Collections.reverseOrder()); //Sort the array in alphabetical order System.out.println(Arrays.toString(str)); //Display the array > > 

Enter the number of elements
5
Enter the String
Mumbai
Pune
Chennai
Ranchi
Kolkata
[Ranchi, Pune, Mumbai ,Kolkata, Chennai]

Источник

4 ways in Java to sort a String alphabetically

This blog will show you how to sort a String alphabetically in Java . For example, the String ‘albert’ will become ‘abelrt’ after sorting. Since String is immutable, it will create a new String with the sorted characters. We will learn four different ways with examples in this post.

Method 1: By using two loops:

This is the simplest way to sort a String . We will use two for loops and one loop will run inside another loop. The outer loop will iterate over the characters one by one and for each character, the inner loop will compare it with all other characters to the right of that character. If any alphabetically small character is found by the inner loop, it will swap it with the character pointed by the outer loop.

The following program shows how to write this in Java :

import java.util.Scanner; class FirstExample  public static void main(String[] args)  try (Scanner scanner = new Scanner(System.in))  System.out.println("Enter a string:"); String userInput = scanner.nextLine(); char[] charArray = userInput.toCharArray(); for (int i = 0; i  charArray.length; i++)  for (int j = i + 1; j  charArray.length; j++)  if (Character.toLowerCase(charArray[j])  Character.toLowerCase(charArray[i]))  swapChars(i, j, charArray); > > > System.out.println("Sorted string " + String.valueOf(charArray)); > > private static void swapChars(int i, int j, char[] charArray)  char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; > >

The commented numbers in the above program denote the step numbers below:

Create one Scanner object to read the user input String .

Ask the user to enter a String . Read it and assign it to the userInput variable.

We need to compare each character of this String , swap, and arrange them in ascending order. Since a String is immutable, we need to convert the String to an Array . It is using the toCharArray() method to convert it to an array of characters. It assigns the value to the charArray variable.

It uses two nested for loops to sort the characters of the array. It converts the characters to lowercase before comparing.

The swapChars method is used to swap two characters in an array. It takes the position of the characters in an array and the array as its parameters. If the character at index j is smaller than the character at index i , it swaps the characters of these positions.

Finally, print out the sorted string to the user. It uses the String.valueOf method to convert the character array to String .

If you run the above program, it will print outputs as below:

Enter a string : Alphabet Sorted string Aabehlpt Enter a string : elephant Sorted string aeehlnpt

Method 2: Sort a String by converting it to an Array :

The previous method converts the String to an array of characters and used two for loops to sort the characters. We can also use the Arrays.sort method to sort the content of the character array. The sorted array can be converted back to a String .

The following program shows how it works:

import java.util.Arrays; import java.util.Scanner; class SecondExample  public static void main(String[] args)  try (Scanner scanner = new Scanner(System.in))  System.out.println("Enter a string:"); String userInput = scanner.nextLine(); char[] charArray = userInput.toCharArray(); Arrays.sort(charArray); System.out.println("Sorted string: " + String.valueOf(charArray)); > > >

The only problem with this method is that it will fail to sort a string with both uppercase and lowercase letters. If the String has only uppercase or lowercase letters, it will work.

Enter a string: Elephant Sorted string: Eaehlnpt Enter a string: elephant Sorted string: aeehlnpt Enter a string: ELEPHANT Sorted string: AEEHLNPT

As you can see here, the first example failed as the ASCII value of E is 69 and the ASCII value of a is 97. So, it placed E before a .

Java sort string example

Method 3: How to sort a String by using a comparator:

We can use a Comparator with the Arrays.sort() method. We need to convert the string to a Character array. The following program shows how to sort a given String with a comparator:

import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; class ThirdExample  public static void main(String[] args)  try (Scanner scanner = new Scanner(System.in))  System.out.println("Enter a string:"); String userInput = scanner.nextLine(); Character[] charArray = new Character[userInput.length()]; for (int i = 0; i  userInput.length(); i++)  charArray[i] = userInput.charAt(i); > Arrays.sort(charArray, Comparator.comparingInt(Character::toLowerCase)); StringBuilder sb = new StringBuilder(charArray.length); for (Character c : charArray) sb.append(c.charValue()); System.out.println("Sorted string: " + sb.toString()); > > >
  1. It creates one Character array from the string. It is assigned to the charArray variable.
  2. It passes one lambda function to the sort method.
Arrays.sort(charArray, new Comparator()  @Override public int compare(Character o1, Character o2)  return Character.compare(Character.toLowerCase(o1), Character.toLowerCase(o2)); > >);

Finally, it converts the character array to a StringBuilder object and it is converted back to String by using the toString() method.

The above program will print output as below:

Enter a string: Elephant Sorted string: aEehlnpt

Method 4: Sort a String by using Stream :

Another way is to use the Stream API to sort the characters. We can convert the String to a Stream , sort the characters and convert it back to a String . The following program shows how it works:

import java.util.Comparator; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.Stream; class FourthExample  public static void main(String[] args)  try (Scanner scanner = new Scanner(System.in))  System.out.println("Enter a string:"); String userInput = scanner.nextLine(); String finalString = Stream.of(userInput.split("")) .sorted(Comparator.comparingInt(o -> Character.toLowerCase(o.charAt(0)))) .collect(Collectors.joining()); System.out.println("Sorted string: " + finalString); > > >

We are using the same comparator function in the sorted() method. If you run the program, it will print output as below:

Enter a string: Elephant Sorted string: aEehlnpt

java sort string character alphabetically

We have learned four different ways to sort the characters in a string in Java. You can raise a PR on GitHub if you want to add anything else.

Источник

Оцените статью