gpt4 book ai didi

scala - 在 Scala 中使用 Ordered[String] 对字符串进行排序?

转载 作者:行者123 更新时间:2023-12-05 01:16:56 25 4
gpt4 key购买 nike

我需要在 Java 和 Scala 中具有与 compareWith(a,b) 方法等效的方法。

我有一个字符串列表,我需要通过相互比较对它们进行排序。 sortBy 只接受一个字符串并返回一个分数,但在我的情况下这还不够,我需要将两个字符串相互比较,然后根据哪个更好返回一个数字。

似乎唯一的选择是编写自定义案例类,将字符串转换为它,然后再将它们隐藏回去。出于性能原因,我想避免这种情况,因为我要处理大量数据。

有没有办法只用字符串来做到这一点?

最佳答案

我想你在找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.

例子:

List("Steve", "Tom", "John", "Bob").sortWith(_.compareTo(_) < 0) =
List("Bob", "John", "Steve", "Tom")

关于scala - 在 Scala 中使用 Ordered[String] 对字符串进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52288365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com