Problem
你有一个集合,内部有很多重复元素,你想要把这些重复的元素只保留一份。
Solution
使用Distinct方法:
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集合。
如果你突然需要一个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的实例。
Using distinct with your own classes
要想对你自己定义的集合元素类型使用distinct方法,你需要实现equals和hashCode方法。举个例子,下面这个类就可以使用disticnt方法,因为我们实现了这两个方法:
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> 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)
来源:oschina
链接:https://my.oschina.net/u/2633112/blog/661150