你有一個集合,內部有不少重複元素,你想要把這些重複的元素只保留一份。
app
使用Distinct方法:ide
scala> val x = Vector(1, 1, 2, 3, 3, 4) x: scala.collection.immutable.Vector[Int] = Vector(1, 1, 2, 3, 3, 4) scala> val y = x.distinct y: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4)
這個distinct方法返回一個新的集合,重複元素只保留一份。記得使用一個新的變量來指向這個新的集合,不管你使用的是mutable集合仍是immutable集合。oop
若是你忽然須要一個set,那麼直接吧你的集合轉化成爲一個set也是去掉重複元素的方式:
測試
scala> val s = x.toSet s: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)
由於Set對於同樣的元素只能保存一份,因此把Array,List,Vector或者其餘的集合轉化成Set能夠去掉重複元素。實際上這就是distinct方法的工做遠離。Distinct方法的源代碼顯示了他就是實用了一個mutable.HashSet的實例。this
要想對你本身定義的集合元素類型使用distinct方法,你須要實現equals和hashCode方法。舉個例子,下面這個類就能夠使用disticnt方法,由於咱們實現了這兩個方法:
url
class Person(firstName: String, lastName: String) { override def toString = s"$firstName $lastName" def canEqual(a: Any) = a.isInstanceOf[Person] override def equals(that: Any): Boolean = { that match { case that: Person => that.canEqual(this) && this.hashCode == that.hashCode case _ => false } } override def hashCode: Int = { val prime = 31 var result = 1 result = prime * result + lastName.hashCode result = prime * result + (if(firstName == null) 0 else firstName.hashCode) return result } } scala> class Person(firstName: String, lastName: String) { | override def toString = s"$firstName $lastName" | def canEqual(a: Any) = a.isInstanceOf[Person] | override def equals(that: Any): Boolean = { | that match { | case that: Person => that.canEqual(this) && this.hashCode == that.hashCode | case _ => false | } | } | override def hashCode: Int = { | val prime = 31 | var result = 1 | result = prime * result + lastName.hashCode | result = prime * result + (if(firstName == null) 0 else firstName.hashCode) | return result | } | } defined class Person object Person { def apply(firstName: String, lastName: String) = new Person(firstName, lastName) } scala> object Person { | def apply(firstName: String, lastName: String) = new Person(firstName, lastName) | } defined module Person
接下來咱們定義幾個Person對象的實例,並測試distinct方法:scala
scala> val dale1 = new Person("Dale", "Cooper") dale1: Person = Dale Cooper scala> val dale2 = new Person("Dale", "Cooper") dale2: Person = Dale Cooper scala> val ed = new Person("Ed", "Hurley") ed: Person = Ed Hurley scala> val list = List(dale1, dale2, ed) list: List[Person] = List(Dale Cooper, Dale Cooper, Ed Hurley) scala> val uniques = list.distinct uniques: List[Person] = List(Dale Cooper, Ed Hurley)