List an Array of Strings in alphabetical order

Nick Mico picture Nick Mico · Feb 18, 2013 · Viewed 208.7k times · Source

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);

Answer

Vineet Kosaraju picture Vineet Kosaraju · Feb 18, 2013

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