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
Answer from Vineet Kosaraju on Stack OverflowWeird, 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
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));
}
}
Videos
So i have an arraylist where each index contains a book which consists of two strings, Author and Title.
How do i sort the list by authors alphabetically?
Any suggestions are appriciated, thanks!
Assuming you are running some variation of the bubble sort algorithm, and that you have not sanitised you input array for null strings, the problem is likely that organizedNames[i] is null.
If this is the case you need to decide if you want to remove null items, or list them at the end of the array. If the latter is true, prior to doing a comparison, check if name1 == null || name2 == null if so, set num to -1, this will put all the null items in an array in one place.
To answer your secondary question, try this:
boolean done = false;
while(done == false){
done = true;
for(int i=0;i<organizedNames.length-1;i++)
{
int num = 0;
if(organizedNames[i] != null && organizedNames[i + 1] != null)
{
String name1=organizedNames[i]; String name2=organizedNames[i+1];
num=name1.compareTo(name2);
}
else if(organizedNames[i] == null && organizedNames[i + 1] == null){
num = 0;
}
else if(organizedNames[i] == null){
num = 1;
}
else {
num = -1;
}
if(num>0)
{
String temp=organizedNames[i];
organizedNames[i]=organizedNames[i+1];
organizedNames[i+1]=temp;
done=false;
}
}
}
Using collections we can do like this..
SortedSet<String> set = new TreeSet<String>();
String[] s = { "this", "will", "be", "sorted", "without", "ba", "any", "sort()", "function", "or","comparator" };
for (int i = 0; i < s.length; i++)
{
set.add(s[i]);
}
for (Object element : set) {
System.out.println(element.toString());
}