如果你想用列表來做到這一點,使用groupBy
:
l.groupBy(x => (x._1, x._2)).map(kv => kv._2.head).toList
如果你真的想要爲所有集合類型是通用的:
scala> import scala.collection.generic.CanBuildFrom
import scala.collection.generic.CanBuildFrom
scala> def distinct[A, B, C, CC[X] <: Traversable[X]](xs: CC[(A, B, C)])(implicit cbf: CanBuildFrom[Nothing, (A, B, C), CC[(A, B, C)]]): CC[(A, B, C)] = xs.groupBy(x => (x._1, x._2)).map(kv => kv._2.head).to[CC]
warning: there were 1 feature warnings; re-run with -feature for details
distinct: [A, B, C, CC[X] <: Traversable[X]](xs: CC[(A, B, C)])(implicit cbf: scala.collection.generic.CanBuildFrom[Nothing,(A, B, C),CC[(A, B, C)]])CC[(A, B, C)]
scala> distinct(List((1, 2, "ok"), (1, 3, "ee"), (1, 2, "notok")))
res0: List[(Int, Int, String)] = List((1,3,ee), (1,2,ok))
是否需要保留元素的排序? – sschaef
@sschaef不需要保留順序。 – Jus12
[Scala:刪除對象列表中的重複項]的可能重複(http://stackoverflow.com/questions/3912753/scala-remove-duplicates-in-list-of-objects) –