这个例子还是蛮具有代表性的,主要练习访问文件读取文件,Map键值对使用,foreach遍历,匿名函数
代码语言:javascript复制import java.io.File
import scala.io.Source
class WordsCount{
def subdirs(dir: File): Iterator[File] = {
val children = dir.listFiles.filter(_.isFile)
children.toIterator
}
def getWordNum(file: Iterator[File]):scala.collection.mutable.Map[String, Int]={
val wordsMap = scala.collection.mutable.Map[String, Int]()
file.foreach(file => Source.fromFile(file).getLines().foreach(line=>line.split(" ").foreach(
word=>{
if (wordsMap.contains(word)){
wordsMap(word) =1
}
else{
wordsMap(word)=1
}
}
)))
wordsMap
}
}
object WordCount {
def main(args: Array[String]): Unit = {
val wc = new WordsCount()
val dir = new File("E:\scala")
val wordsMap = wc.getWordNum(wc.subdirs(dir))
for ((k, v) <- wordsMap)
{
println(k ":" v)
}
}
}