简体   繁体   中英

Scala Seq comparison

is there a way in Scala to compare two sequences in a way that it returns true if it contains the same elements, regardless of order and repetitions?

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

Thanks

ps this is not a duplicated of this because it also asks to exclude duplicated from the check and it is using SEQ instead of LIST.

转换为集合并进行比较

@ 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

Introduce an extension object with === operator. It will be used implicitly for the same typed 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

You just need to turn the sequences to sets:

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.")
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM