Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to sort a Linked List?

I am needing to sort a linked list alphabetically. I have a Linked List full of passengers names and need the passengers name to be sorted alphabetically. How would one do this? Anyone have any references or videos?

like image 713
allencoded Avatar asked Jun 06 '11 02:06

allencoded


2 Answers

You can use Collections#sort to sort things alphabetically.

like image 121
mre Avatar answered Oct 21 '22 12:10

mre


In order to sort Strings alphabetically you will need to use a Collator, like:

 LinkedList<String> list = new LinkedList<String>();
 list.add("abc");
 list.add("Bcd");
 list.add("aAb");
 Collections.sort(list, new Comparator<String>() {
     @Override
     public int compare(String o1, String o2) {
         return Collator.getInstance().compare(o1, o2);
     }
 });

Because if you just call Collections.sort(list) you will have trouble with strings that contain uppercase characters.

For instance in the code I pasted, after the sorting the list will be: [aAb, abc, Bcd] but if you just call Collections.sort(list); you will get: [Bcd, aAb, abc]

Note: When using a Collator you can specify the locale Collator.getInstance(Locale.ENGLISH) this is usually pretty handy.

like image 27
Federico Vera Avatar answered Oct 21 '22 12:10

Federico Vera