Reputation: 267059
I need to have an equivalent of the compareWith(a,b)
method in Java, in Scala.
I have a list of strings and I need to sort them by comparing them with each other. sortBy
just takes one string and returns a score, but that's not enough in my case, i need to compare two strings with each other and then return a number based on which one is better.
It seems like the only option is to write a custom case class, convert the strings to it, and then covert them back. For performance reasons, I want to avoid this as I have a large amount of data to process.
Is there a way to do this with just the strings?
Upvotes: 3
Views: 4597
Reputation: 262494
I think you are looking for sortWith
.
sortWith(lt: (A, A) ⇒ Boolean): Repr
Sorts this sequence according to a comparison function.
Note: will not terminate for infinite-sized collections.
The sort is stable. That is, elements that are equal (as determined by lt) appear in the same order in the sorted sequence as in the original.
lt
the comparison function which tests whether its first argument precedes its second argument in the desired ordering.
Example:
List("Steve", "Tom", "John", "Bob").sortWith(_.compareTo(_) < 0) =
List("Bob", "John", "Steve", "Tom")
Upvotes: 7