I have a string arraylist called names. How do I sort the arraylist in alphabetical order?
-
6Dude, google "sort arraylist java". The first hit shows you the answer. And this question has nothing to do with Android, it's plain Java. – Flo Apr 28 '11 at 07:03
-
@Flo indeed, but then I tried to link a dupe in here and everything was more complex, I could not find any question for the very basic stuff (the closes was to sort an `ArrayList
`). It may be here and I may have missed, though. – Aleadam Apr 28 '11 at 07:07
3 Answers
ArrayList<String> names = new ArrayList<String>();
names =fillNames() // whatever method you need to fill here;
Collections.sort(names);
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
String
implements Comparable
:
java.lang Class String
java.lang.Object extended by java.lang.String
All Implemented Interfaces: Serializable, CharSequence, Comparable
http://download.oracle.com/javase/6/docs/api/java/lang/String.html

- 40,203
- 9
- 86
- 108
Another solution but Collections.sort()
is best. I just want to show alternative
ArrayList<String> strings = new ArrayList<String>();
strings.add("a");
strings.add("ab");
strings.add("aa");
String[] stringsArray = new String[strings.size()];
strings.toArray(stringsArray);
Arrays.sort(stringsArray);
List<String> sorted = Arrays.asList(stringsArray);
System.out.println(sorted);
import java.util.Collections;
then use Collections.sort();

- 155
- 7
-
i am using android platform.is it possible to use this same code in android? – andro-girl Apr 28 '11 at 07:13