How can I sort a List alphabetically? How can I sort a List alphabetically? java java

How can I sort a List alphabetically?


Assuming that those are Strings, use the convenient static method sort

 java.util.Collections.sort(listOfCountryNames)


Solution with Collections.sort

If you are forced to use that List, or if your program has a structure like

  • Create List
  • Add some country names
  • sort them once
  • never change that list again

then Thilos answer will be the best way to do it. If you combine it with the advice from Tom Hawtin - tackline, you get:

java.util.Collections.sort(listOfCountryNames, Collator.getInstance());

Solution with a TreeSet

If you are free to decide, and if your application might get more complex, then you might change your code to use a TreeSet instead. This kind of collection sorts your entries just when they are inserted. No need to call sort().

Collection<String> countryNames =     new TreeSet<String>(Collator.getInstance());countryNames.add("UK");countryNames.add("Germany");countryNames.add("Australia");// Tada... sorted.

Side note on why I prefer the TreeSet

This has some subtle, but important advantages:

  • It's simply shorter. Only one line shorter, though.
  • Never worry about is this list really sorted right now becaude a TreeSet is always sorted, no matter what you do.
  • You cannot have duplicate entries. Depending on your situation this may be a pro or a con. If you need duplicates, stick to your List.
  • An experienced programmer looks at TreeSet<String> countyNames and instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration.
  • Real performance win in some cases. If you use a List, and insert values very often, and the list may be read between those insertions, then you have to sort the list after every insertion. The set does the same, but does it much faster.

Using the right collection for the right task is a key to write short and bug free code. It's not as demonstrative in this case, because you just save one line. But I've stopped counting how often I see someone using a List when they want to ensure there are no duplictes, and then build that functionality themselves. Or even worse, using two Lists when you really need a Map.

Don't get me wrong: Using Collections.sort is not an error or a flaw. But there are many cases when the TreeSet is much cleaner.


You can create a new sorted copy using Java 8 Stream or Guava:

// Java 8 versionList<String> sortedNames = names.stream().sorted().collect(Collectors.toList());// Guava versionList<String> sortedNames = Ordering.natural().sortedCopy(names); 

Another option is to sort in-place via Collections API:

Collections.sort(names);