Scala 序列比较
Scala Seq comparison
在 Scala 中有没有一种方法可以比较两个序列,如果它包含相同的元素,则 returns 为真,而不考虑顺序和重复?
Seq("1", "2") vs Seq("2", "1") => true
Seq("3", "1", "2") vs Seq("2", "1", "3") => true
Seq("1", "1", "2") vs Seq("2", "1") => true
谢谢
ps 这不是 this 的重复项,因为它还要求从检查中排除重复项,并且它使用的是 SEQ 而不是 LIST。
转换为集合并进行比较
引入一个带有===操作符的扩展对象。
它将隐式用于相同类型的 Seqs
implicit class SeqOps[A](it:Seq[A]){
def === (that:Seq[A]) = it.toSet == that.toSet
}
import Test.SeqOps
Seq("1", "2") === Seq("2", "1") shouldBe true
您只需要将序列转为集合:
val n1: Seq[Int] = Seq(1, 3, 4)
val n2: Seq[Int] = Seq(3, 4, 1)
if(n1.toSet.equals(n2.toSet)){
println("The sequences have the same elements.")
}
@ def sameElements[A](a: Seq[A], b: Seq[A]) = a.toSet == b.toSet
defined function sameElements
@ sameElements(Seq("1", "2"),Seq("2", "1"))
res2: Boolean = true
@ sameElements(Seq("3", "1", "2"),Seq("2", "1", "3"))
res3: Boolean = true
@ sameElements(Seq("1", "1", "2"),Seq("2", "1"))
res4: Boolean = true
在 Scala 中有没有一种方法可以比较两个序列,如果它包含相同的元素,则 returns 为真,而不考虑顺序和重复?
Seq("1", "2") vs Seq("2", "1") => true
Seq("3", "1", "2") vs Seq("2", "1", "3") => true
Seq("1", "1", "2") vs Seq("2", "1") => true
谢谢
ps 这不是 this 的重复项,因为它还要求从检查中排除重复项,并且它使用的是 SEQ 而不是 LIST。
转换为集合并进行比较
引入一个带有===操作符的扩展对象。 它将隐式用于相同类型的 Seqs
implicit class SeqOps[A](it:Seq[A]){
def === (that:Seq[A]) = it.toSet == that.toSet
}
import Test.SeqOps
Seq("1", "2") === Seq("2", "1") shouldBe true
您只需要将序列转为集合:
val n1: Seq[Int] = Seq(1, 3, 4)
val n2: Seq[Int] = Seq(3, 4, 1)
if(n1.toSet.equals(n2.toSet)){
println("The sequences have the same elements.")
}
@ def sameElements[A](a: Seq[A], b: Seq[A]) = a.toSet == b.toSet
defined function sameElements
@ sameElements(Seq("1", "2"),Seq("2", "1"))
res2: Boolean = true
@ sameElements(Seq("3", "1", "2"),Seq("2", "1", "3"))
res3: Boolean = true
@ sameElements(Seq("1", "1", "2"),Seq("2", "1"))
res4: Boolean = true