【问题标题】:Scala-A function about 'contains'Scala-A 关于“包含”的函数
【发布时间】:2018-08-15 01:05:26
【问题描述】:

如果我想有一个功能可以实现对某些值的筛选。

E.g val strings = List("a", "b", "c", "e", "r")
val SpecificStrings = List("a", "b", "d")

通过函数,我会得到结果:

List("a", "b")

那么我应该如何编写这个函数呢?Thx

【问题讨论】:

    标签: string scala rdd contains


    【解决方案1】:

    就这样吧:

    strings.intersect(SpecificStrings)
    

    不要自己编写函数。

    【讨论】:

      【解决方案2】:

      在 Scala 中有多种方法可以实现相同的结果

      使用过滤器

      strings.filter(SpecificStrings.contains(_))
      //res0: List[String] = List(a, b)
      

      使用 ListBuffer 和 for 循环

      val listBuffer = new ListBuffer[String]
      for(str <- strings){
        if(SpecificStrings.contains(str)){
          listBuffer += str
        }
      }
      listBuffer.toList
      //res1: List[String] = List(a, b)
      

      也有递归方法,但递归方法每次递归都需要一个新的堆栈帧,不适合大型数据集。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-19
        • 1970-01-01
        • 2021-03-29
        • 2020-01-21
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 2021-08-30
        相关资源
        最近更新 更多