分享

请教个flatmap的问题。。

dsy198816 发表于 2017-2-8 11:56:12 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 4 7005
我需要处理一些很复杂的匹配逻辑,我需要自定义一个匹配方法def  然后再flatmap里调用改如何实现,下面是我的测试代码flatmap那里编译不过。
object SimpleApp {

    def matchword(ps: String): List ={
        if(ps.equals("fsda"))
            List(ps)
    }

    def main(args: Array[String]) {
        val conf = new SparkConf().setAppName("Simple Application")
        val sc = new SparkContext(conf)
        val line = sc.parallelize(List("fdsa", "dsfsf", "dwfegw", "yureq", "acvd", "fgvb"))
        
        val words = line.flatMap(matchword(x))
        words.foreach(println)
        sc.stop()
    }
}

已有(4)人评论

跳转到指定楼层
tntzbzc 发表于 2017-2-8 12:37:03
val words = line.flatMap(SimpleApp.matchword(x))
或则作为匿名函数直接写到flatMap里面


回复

使用道具 举报

desehawk 发表于 2017-2-8 16:36:05
def matchword(ps: String): List ={
        if(ps.equals("fsda"))
            List(ps)
    }
如果不等于fsda,返回的是什么,最好定义下。如果不是List ,会不会出问题

回复

使用道具 举报

starrycheng 发表于 2017-2-8 17:12:39
具体报的什么错误
回复

使用道具 举报

ledasion 发表于 2017-2-10 16:48:51
import org.apache.spark.{SparkConf,SparkContext}

object SimpleApp {

    def matchword(ps: String): List [String]={
      var list:List[String]=null  
      if(ps.equals("fsda"))
            list:+= ps
      list
    }

    def main(args: Array[String]) {
        val conf = new SparkConf().setAppName("Simple Application")
        val sc = new SparkContext(conf)
        val line = sc.parallelize(List("fdsa", "dsfsf", "dwfegw", "yureq", "acvd", "fgvb"))
        
        val words = line.flatMap(x => matchword(x))
        words.foreach(println)
        sc.stop()
    }
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条