I have two names from a user.
I want to compare them and display them in alphabetical order.
I tried the compareTo method, but that only returns an int.
EDIT: Answer found! Thanks again guys!
I have two names from a user.
I want to compare them and display them in alphabetical order.
I tried the compareTo method, but that only returns an int.
EDIT: Answer found! Thanks again guys!
The easiest way is to store them in a data structure such as TreeSet
which inherently sort their contents (usually by calling compareTo
internally).
Otherwise there is also the Collections.sort
static method to sort an existing List
.
There are sorting methods built into Java. Try putting the names into an array and using an Array sort.
You need to sort them (the compareTo method gives the sorting algorithm the information it needs to know what goes before what). To sort them, you need to put them in a List, then use the Collections.sort() method.
Here's an example for you, assuming that you have more than just two names, though it will work for that as well:
// Create a list
String[] strArray = new String[] {"z", "a", "C"};
List list = Arrays.asList(strArray);
// Sort
Collections.sort(list);
// C, a, z
// Case-insensitive sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
// a, C, z
// Reverse-order sort
Collections.sort(list, Collections.reverseOrder());
// z, a, C
// Case-insensitive reverse-order sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(list);
// z, C, a
You say: "I have to names" -- assuming that you meant "I have two names"...
If you have two strings, then you have only two possible ways you can return them. It's either A, B or B, A. There are only three possible ways the two strings can be ordered.
Either:
As it turns out, according to the Java documentation, the String.compareTo()
method actually gives you a value that maps to those three possible states:
The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
IF you only have two names, use the compareTo() approach. If you've got a lot, use the other solutions (adding them to a List and sorting it).
Always prefer "Arrays.asList(strArray);" to "new ArrayList()" and when not possible, for the sake of performance, specify the list size on constructor.