你有一个集合,内部有不少重复元素,你想要把这些重复的元素只保留一份。
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)