我在scala中有一段代码
val wordCounts = logData.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey((a, b) => a + b)
wordCounts.foreach(println(_))那么println(_)是什么意思,它应该打印什么?
发布于 2018-09-19 23:35:31
正如规范中的“匿名函数占位符语法”一节所解释的那样,
println(_)是匿名函数文字的快捷方式。
w => println(w)这反过来又是类似于
(w: (String, Int)) => println(w)在这种特殊的情况下。
因此,
wordCounts.foreach(println(_))只需打印wordCounts的每个元素即可。
请注意,它也可以写得更短:
wordCounts foreach printlnhttps://stackoverflow.com/questions/52415502
复制相似问题