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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With