Scala Seq比较

时间:2016-01-08 19:37:33

标签: scala seq

Scala有没有办法比较两个序列,如果它包含相同的元素,它返回true,无论顺序和重复如何?

@Override
public boolean equals(Object o) {
    if(o == null)
        return false;

    // in case you tried to compare a Card with a Not-a-Card object
    if(!o instanceof Card) 
        return false;

    Card c = (Card) o;

    return rank.equals(c.rank) && suit.equals(c.suit) && val == c.val;
}

由于

ps这不是this的重复,因为它还要求从支票中排除重复,它使用的是SEQ而不是LIST。

4 个答案:

答案 0 :(得分:10)

转换为集并比较

答案 1 :(得分:0)

@ 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

答案 2 :(得分:-1)

使用===运算符引入扩展对象。 它将隐式用于相同类型的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

答案 3 :(得分:-3)

您只需将序列转换为集合:

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