Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting strings using Ordered[String] in Scala?

Tags:

scala

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?

like image 417
Ali Avatar asked Jun 03 '26 16:06

Ali


1 Answers

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")
like image 58
Thilo Avatar answered Jun 06 '26 05:06

Thilo



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!