Reputation: 455
I have a set of a certain dto i created.
The dto is named "NumericValue", and has the following class members: 1) time: Long 2) value: Double
I have a set named "points", and i want to sort it according to increasing time, i.e. 0, 1, 2, 4, 100,...
Attached is code:
val points: set(NumericValue) = numericValueSet
val setSorted = collection.immutable.SortedSet[Long]() ++ points
I did the following:
However the result isn't sorted according to time.
Thanks
Upvotes: 0
Views: 1004
Reputation: 10671
Result isn't unsorted because there is not Ordering
for your class.
You can explicit implement Ordered
:
case class NumericValue(time: Long, value: Double) extends Ordered[NumericValue] {
override def compare(that: NumericValue): Int =
Ordering[Long].compare(this.time, that.time)
}
or create Ordering
for your set:
val set = SortedSet[NumericValue]()(new Ordering[NumericValue]() {
override def compare(x: NumericValue, y: NumericValue): Int =
Ordering[Long].compare(x.time, y.time)
})
Result should be ordered:
set + NumericValue(345, 45) + NumericValue(453, 123) + NumericValue(5, 5)
res0: scala.collection.SortedSet[NumericValue] = TreeSet(NumericValue(5,5.0), NumericValue(345,45.0), NumericValue(453,123.0))
Upvotes: 9