1// java sort string characters alphabetically
2import java.util.Arrays;
3public class CharactersAlphabetically
4{
5 public static void main(String[] args)
6 {
7 String strInput = "flowerbrackets";
8 // converting string to char array
9 char[] ch = strInput.toCharArray();
10 // sorting char array
11 Arrays.sort(ch);
12 // converting char array to string
13 String strSorted = String.valueOf(ch);
14 System.out.println("sort string characters alphabetically: " + strSorted);
15 }
16}
1import java.util.Scanner;
2public class SortNamesAlphabeticalOrder
3{
4 public static void main(String[] args)
5 {
6 int number;
7 String str;
8 Scanner sc1 = new Scanner(System.in);
9 System.out.println("Please enter number of strings: ");
10 number = sc1.nextInt();
11 String[] names = new String[number];
12 Scanner sc2 = new Scanner(System.in);
13 System.out.println("Enter all strings: ");
14 for(int a = 0; a < number; a++)
15 {
16 names[a] = sc2.nextLine();
17 }
18 for(int a = 0; a < number; a++)
19 {
20 for(int b = a + 1; b < number; b++)
21 {
22 // java alphabetical sort
23 if(names[a].compareTo(names[b]) > 0)
24 {
25 str = names[a];
26 names[a] = names[b];
27 names[b] = str;
28 }
29 }
30 }
31 System.out.println("After sorting names in an alphabetical order: ");
32 for(int a = 0; a < number - 1; a++)
33 {
34 System.out.println(names[a] + ", ");
35 }
36 System.out.print(names[number - 1]);
37 sc1.close();
38 sc2.close();
39 }
40}
1Assuming that those are Strings, use the convenient static method sort…
2
3 java.util.Collections.sort(listOfCountryNames)
1// Arrange words of a sentence in alphabetical order in java
2import java.util.Set;
3import java.util.StringTokenizer;
4import java.util.TreeSet;
5public class ArrangeInAlphabeticalOrder
6{
7 public static void main(String[] args)
8 {
9 Set set = new TreeSet();
10 String strInput = "hi all welcome to flower brackets blog";
11 System.out.println("Before arranging sentence in alphabetical order: " + strInput);
12 StringTokenizer strToken = new StringTokenizer(strInput," ");
13 while(strToken.hasMoreElements())
14 {
15 set.add(strToken.nextElement());
16 }
17 System.out.println("After arranging sentence in alphabetical order: " + set);
18 }
19}