Java how to sort a Linked List?
You can use Collections#sort
to sort things alphabetically.
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.
In java8 you no longer need to use Collections.sort method as LinkedList inherits the method sort from java.util.List, so adapting Fido's answer to Java8:
LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");
list.sort( new Comparator<String>(){
@Override
public int compare(String o1,String o2){
return Collator.getInstance().compare(o1,o2);
}
});
References:
http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html
http://docs.oracle.com/javase/7/docs/api/java/util/List.html
Elegant solution since JAVA 8:
LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");
list.sort(String::compareToIgnoreCase);
Another option would be using lambda expressions:
list.sort((o1, o2) -> o1.compareToIgnoreCase(o2));