[java] List an Array of Strings in alphabetical order

I have a program which has the user inputs a list of names. I have a switch case going to a function which I would like to have the names print off in alphabetical order.

public static void orderedGuests(String[] hotel)
{
  //??
}

I have tried both

Arrays.sort(hotel);
System.out.println(Arrays.toString(hotel));

and

java.util.Collections.sort(hotel);

This question is related to java arrays function case

The answer is


The first thing you tried seems to work fine. Here is an example program.
Press the "Start" button at the top of this page to run it to see the output yourself.

import java.util.Arrays;

public class Foo{
    public static void main(String[] args) {
        String [] stringArray = {"ab", "aB", "c", "0", "2", "1Ad", "a10"};
        orderedGuests(stringArray);
    }

    public static void orderedGuests(String[] hotel)
    {
        Arrays.sort(hotel);
        System.out.println(Arrays.toString(hotel));
    }
}

Here is code that works:

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

public class Test
{
    public static void main(String[] args)
    {
        orderedGuests1(new String[] { "c", "a", "b" });
        orderedGuests2(new String[] { "c", "a", "b" });
    }

    public static void orderedGuests1(String[] hotel)
    {
        Arrays.sort(hotel);
        System.out.println(Arrays.toString(hotel));
    }

    public static void orderedGuests2(String[] hotel)
    {
        Collections.sort(Arrays.asList(hotel));
        System.out.println(Arrays.toString(hotel));
    }

}

 public static String[] textSort(String[] words) {
    for (int i = 0; i < words.length; i++) {
        for (int j = i + 1; j < words.length; j++) {
            if (words[i].compareTo(words[j]) > 0) {
                String temp = words[i];
                words[i] = words[j];
                words[j] = temp;
            }
        }
    }

    return words;
}

**//With the help of this code u not just sort the arrays in alphabetical order but also can take string from user or console or keyboard

import java.util.Scanner;
import java.util.Arrays;
public class ReadName
{
final static int ARRAY_ELEMENTS = 3;
public static void main(String[] args)
{
String[] theNames = new String[5];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the names: ");
for (int i=0;i<theNames.length ;i++ )
{           
theNames[i] = keyboard.nextLine();
}
System.out.println("**********************");
Arrays.sort(theNames);
for (int i=0;i<theNames.length ;i++ )
{
System.out.println("Name are " + theNames[i]);
}
}
}**

You can just use Arrays#sort(), it's working perfectly. See this example :

String [] a = {"English","German","Italian","Korean","Blablablabla.."};
//before sort
for(int i = 0;i<a.length;i++)
{
  System.out.println(a[i]);
}
Arrays.sort(a);
System.out.println("After sort :");
for(int i = 0;i<a.length;i++)
{
  System.out.println(a[i]);
}

You can use Arrays.sort() method. Here's the example,

import java.util.Arrays;

public class Test 
{
    public static void main(String[] args) 
    {
        String arrString[] = { "peter", "taylor", "brooke", "frederick", "cameron" };
        orderedGuests(arrString);
    }

    public static void orderedGuests(String[] hotel)
    {
        Arrays.sort(hotel);
        System.out.println(Arrays.toString(hotel));
    }
}

Output

[brooke, cameron, frederick, peter, taylor]


CompareTo() method: The two strings are compared based on Unicode character values.

import java.util.*;

public class Test {

int n,i,temp;
String names[n];

public static void main(String[] args) {
String names[5] = {"Brian","Joshua","Louis","David","Marcus"};

for(i=0;i<5;i++){
    for(j=i+1;i<n;j++){
        if(names[i].CompareTo(names[j]>0) {
             temp=names[i];
             names[i]=names[j];
             names[j]=temp;
         } else
             System.out.println("Alphabetically Ordered");                               
         }
     }                              
}

Arrays.sort(stringArray); This sorts the string array based on the Unicode characters values. All strings that contain uppercase characters at the beginning of the string will be at the top of the sorted list alphabetically followed by all strings with lowercase characters. Hence if the array contains strings beginning with both uppercase characters and lowercase characters, the sorted array would not return a case insensitive order alphabetical list

String[] strArray = { "Carol", "bob", "Alice" };
Arrays.sort(strList);
System.out.println(Arrays.toString(hotel));

Output is : Alice, Carol, bob,

If you require the Strings to be sorted without regards to case, you'll need a second argument, a Comparator, for Arrays.sort(). Such a comparator has already been written for us and can be accessed as a static on the String class named CASE_INSENSITIVE_ORDER.

String[] strArray = { "Carol", "bob", "Alice" };
Arrays.sort(stringArray, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(strArray ));

Output is : Alice, bob, Carol


java.util.Collections.sort(listOfCountryNames, Collator.getInstance());

Weird, your code seems to work for me:

import java.util.Arrays;

public class Test
{
    public static void main(String[] args)
    {
        // args is the list of guests
        Arrays.sort(args);
        for(int i = 0; i < args.length; i++)
            System.out.println(args[i]);
    }
}

I ran that code using "java Test Bobby Joe Angel" and here is the output:

$ java Test Bobby Joe Angel
Angel
Bobby
Joe

By alphabetical-order I assume the order to be : A|a < B|b < C|c... Hope this is what @Nick is(or was) looking for and the answer follows the above assumption.

I would suggest to have a class implement compare method of Comparator-interface as :

public int compare(Object o1, Object o2) {
    return o1.toString().compareToIgnoreCase(o2.toString());
}

and from the calling method invoke the Arrays.sort method with custom Comparator as :

Arrays.sort(inputArray, customComparator);

Observed results: input Array : "Vani","Kali", "Mohan","Soni","kuldeep","Arun"

output(Alphabetical-order) is : Arun, Kali, kuldeep, Mohan, Soni, Vani

Output(Natural-order by executing Arrays.sort(inputArray) is : Arun, Kali, Mohan, Soni, Vani, kuldeep

Thus in case of natural ordering, [Vani < kuldeep] which to my understanding of alphabetical-order is not the thing desired.

for more understanding of natural and alphabetical/lexical order visit discussion here


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to case

PostgreSQL CASE ... END with multiple conditions SQL Server: use CASE with LIKE SQL Server IIF vs CASE SELECT using 'CASE' in SQL SELECT query with CASE condition and SUM() GROUP BY + CASE statement SQL use CASE statement in WHERE IN clause SQL Server - Case Statement where to place CASE WHEN column IS NULL in this query Regarding Java switch statements - using return and omitting breaks in each case