2

I have a string arraylist called names. How do I sort the arraylist in alphabetical order?

Jarrod Dixon
  • 15,727
  • 9
  • 60
  • 72
andro-girl
  • 7,989
  • 22
  • 71
  • 94
  • 6
    Dude, 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 Answers3

3
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

Aleadam
  • 40,203
  • 9
  • 86
  • 108
2

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

import java.util.Collections;

then use Collections.sort();

Polyomino
  • 155
  • 7