How can i sort the dates inside the list?
I have read that this can be achieved by using TreeMap, as it is a sorted and navigable map that organizes elements in a self-balancing binary tree. but its also expensive.
My question is - What is the BEST and EFFICIENT way to achieve the result?
It depends. If you want to have "always sorted" container then TreeSet is your friend. Adding another element to the TreeMap will be O(log(n)) - (very good, faster than linear).
If you need to sort it only once (no adding elements later), then just put it to ArrayList and use sort() method. It will be optimal - O(n log(n))
Update:
As JB Nizet mentioned in the comment, Set (TreeSet) cannot contain duplicates. List (ArrayList) can.
If performance is important and there is a lot of elements and you need to store sorted elements allowing duplicates, then you can store it in TreeSet, but need to implement counting (add() will element.count++, and remove() will element.count-- for example).
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