Is there a method already provided in the Java 5 library to add an element to an alphabetical List?
In other words, say I have a List<String> with three elements {"apple","cat","tree"} and I want to add the String “banana” while keeping the List in alphabetical order; is there an easy way to simply add it to the List, so that the List now has four elements {"apple","banana","cat","tree"}?
You can use a
PriorityQueue. These are sorted according to the comparator of the objects they hold.Stringsare, by default, sorted according to the ASCII values of the first differing character, which will give the results you want (as long as the capitalization of all the words is all the same.)Quick example:
Note that the Big-O runtime of both
add()andpoll()isO(logn).Edit:
PriorityQueueis best if you want to remove the items in order, but you will need aTreeSetto iterate over the collection in order.