Scala学习之List
统计单词出现次数
import scala.collection.mutable
//涉及List与Map
object T7 {
def main(args: Array[String]): Unit = {
var list: List[String] = List("Hello Hadoop", "Hello World", "Hello Scala World", "Hello Scala")
f1(list)
f2(list)
}
def f1(list: List[String]) = {
var list1: List[String] = list.flatMap(_.split(" "))
var map = list1.groupBy(word => word)
var map1 = map.map(kv => {
(kv._1, kv._2.size)
})
var result = map1.toList.sortWith({
(left, right) => {
left._2 > right._2
}
}).take(3)
println(result)
}
def f2(list: List[String]) = {
var list1: List[String] = List()
for (str <- list) {
var arr = str.split(" ")
for (str1 <- arr) {
list1 = list1.+:(str1)
}
}
val map = new mutable.HashMap[String, Int]();
for (str <- list1) {
if (map.keySet.contains(str)) {
map(str) = map(str) + 1
} else {
map.put(str, 1)
}
}
var result = map.toList.sortWith({
(left, right) => {
left._2 > right._2
}
}).take(3)
println(result)
}
}