# Scala 除去List中的重复元素

1, 最简单直接办法是用distinct

scala> val l = List(1,2,3,3,4,4,5,5,6,6,6,8,9)
l: List[Int] = List(1, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6, 8, 9)

scala> l.distinct
res32: List[Int] = List(1, 2, 3, 4, 5, 6, 8, 9)

2, toSet

scala> l.toSet.toList
res33: List[Int] = List(5, 1, 6, 9, 2, 3, 8, 4)

3, 用foldLeft

/**
* List去重(泛型实现)
* @param list
* @tparam T
* @return
*/
def dups[T](list: List[T]) = list.foldLeft(List.empty[T]){
(seen, cur) =>
if(seen.contains(cur)) (seen) else (seen :+ cur)
}
//非泛型实现
def duplicate[Int](list: List[Int]) = list.foldLeft(List.empty[Int]){
(result, cur) => if(result.contains(cur)) result else result :+ cur
}

def main(args: Array[String]) {
//println(countWords("Jack,gates,jack,Lucy:jack,Gates!"))
val dup = List(1,1,1,2,3,4,5,5,6,100,101,101,102)
val list = List("aa","dd","aa","vv","dd")
println(duplicate(dup))
println(dups(dup))
println(dups(list))
}

List(1, 2, 3, 4, 5, 6, 100, 101, 102)
List(1, 2, 3, 4, 5, 6, 100, 101, 102)
List(aa, dd, vv)

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客