Having val hm: HashMap[org.joda.time.DateTime, MyType]
I am trying to get the first and the last DateTime
of the set by means of hm.keys.min
and hm.keys.max
respectively but the compiler says No implicit Ordering defined for org.joda.time.DateTime
. How to define this ordering (both implicit and explicit options are interesting)?
Use the sortWith() Function to Sort List in Scala. We used the sortWith() function to take a lambda expression as an argument and return the sorted result. We can use this function to sort the list in ascending and descending order.
Implicit means the order of items (e.g. codes) as returned within the array of codes. There are thus always naturally given in a structure definition. Explicit order is the order provided through annotations and is optional. Explicit order prevails implicit order.
The first two methods that are used here ("SortedSet" and "TreeSet") are used to sort immutable sets in Scala and take set as input and return the sorted set. The last method is SortedSet working over mutable sets too and take the list conversion of the set to sort.
object Joda { implicit def dateTimeOrdering: Ordering[DateTime] = Ordering.fromLessThan(_ isBefore _) } // elsewhere import Joda._ dateTimes.sorted
To facilitate working with Joda DateTime in Scala, nscala-time was created: https://github.com/nscala-time/nscala-time
After including it in your project with
libraryDependencies += "com.github.nscala-time" %% "nscala-time" % "1.8.0"
you can just import OrderingImplicits
. Either all at once:
import com.github.nscala_time.time.OrderingImplicits._
or a particular one:
import com.github.nscala_time.time.OrderingImplicits.DateTimeOrdering
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