Scala:如何检查 Seq 中的所有项目是否都是唯一的? [英] Scala: How to check if all items are unique in a Seq?

查看:44
本文介绍了Scala:如何检查 Seq 中的所有项目是否都是唯一的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有比此更惯用且可能更快的方法来检查 Seq 中是否存在重复项:

Is there a more idiomatic and maybe faster way to check if there are duplicates in a Seq, than this:

mySeq.size == mySeq.toSet.size

推荐答案

这样会更快,因为它可以提前终止:

This will be faster, because it can terminate early:

def allUnique[A](to: TraversableOnce[A]) = {
  val set = scala.collection.mutable.Set[A]()
  to.forall { x =>
    if (set(x)) false else {
      set += x
      true
    }
  }
}

这篇关于Scala:如何检查 Seq 中的所有项目是否都是唯一的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆