Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort dates in a List

Tags:

java

date

sorting

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?

like image 869
Namita Avatar asked Mar 27 '26 01:03

Namita


1 Answers

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).

like image 137
Michał Šrajer Avatar answered Mar 29 '26 13:03

Michał Šrajer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!