Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 412
Nick Mico Avatar asked Feb 18 '13 21:02

Nick Mico


People also ask

How do you sort an array of strings in alphabetical order?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.

How do you sort a list of strings in alphabetical order in Python?

Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do you alphabetize a string array in Java?

To sort an array of strings in Java, we can use Arrays. sort() function.

Can we sort an array of strings?

To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.


1 Answers

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 
like image 104
Vineet Kosaraju Avatar answered Oct 02 '22 14:10

Vineet Kosaraju