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)








转载于:https://my.oschina.net/brucegao/blog/370402

发布了0 篇原创文章 · 获赞 0 · 访问量 576
展开阅读全文
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符

没有更多推荐了,返回首页

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

分享到微信朋友圈

×

扫一扫,手机浏览