Scala - 比较两个选项[Seq[String]]

标签 scala collections

我是 Scala 语言的新手 - 我似乎在寻找正确的语法来排序和比较两个 Option[Seq[String]] 时遇到问题。无论内容顺序如何,两者都应该相等。此测试的最后一行失败。我希望这段代码足以说明问题。

  package seqtest

import org.scalatest.{Matchers, FlatSpec}

class SortCollectionsTest extends FlatSpec with Matchers {

  "Different seq order" should "not affect equality" in {

    val seqAB1 = Seq("A","B")
    val seqAB2 = Seq("A","B")
    // two different sequences are equal
    assert(seqAB1 == seqAB2)

    val seqBA1 = Seq("B","A")
    // two different sequences are not equal if different order
    assert(seqAB1 != seqBA1)

    // but is possible to convert sequence to list and sort
    assert(seqAB1.toList.sorted == seqBA1.toList.sorted)


    // now do the same thing with Option

    val someSeqAB1 = Some(Seq("A","B"))
    val someSeqAB2 = Some(Seq("A","B"))
    // two different option sequences are equal
    assert(someSeqAB1 == someSeqAB2)

    val someSeqBA = Some(Seq("B","A"))
    // two different optional sequences are not equal if different order
    assert(someSeqAB1 != someSeqBA)

    // Option can be converted into list (unsorted)
    assert(someSeqAB1.toList != someSeqBA.toList)

    // problem
    // two different optional sequences cannot be sorted
    // compilation error
    // Error:(42, 30) No implicit Ordering defined for Seq[String].
    // Error:(42, 30) not enough arguments for method sorted: (implicit ord: scala.math.Ordering[Seq[String]])List[Seq[String]].
    // Unspecified value parameter ord.
    assert(someSeqAB1.toList.sorted == someSeqBA.toList.sorted)
  }
}

最佳答案

我认为更简单的解决方案是映射选项:

assert(someSeqAB1.map{ _.sorted } == someSeqBA.map{ _.sorted })

顺便说一句,对于排序版本来说,断言是相等的。

关于Scala - 比较两个选项[Seq[String]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560262/

相关文章:

java - 如何在 ArrayList 中查找任何重复项的最大值

java - 如何在 Java 中使用 lambda 表达式搜索集合?

java - 对集合性能提示列表进行排序

scala - HTTP4S 客户端。如何获取准确的请求和响应正文

java - 如何重构scala中的增量?

java - 对 JPanel 中的 JButton 进行排序

Java 集合泛型 <?扩展 Employee> 抛出异常

scala - 尽管优先考虑了隐式,为什么我会收到 "ambiguous implicits"错误?

arrays - 寻找一种分割数组的好方法

scala - 在能够处理其他一些消息之前初始化一个actor