1、使用scala的相关函数来统计单词频率
object WordCount {
def main(args: Array[String]): Unit = {
val line = List("hello tom hello jerry","hello xiaobai hello","hello tom")
val words = line.flatMap(_.split(" "))
println("将文本集合切分成单词")
println(words)
val tuples = words.map((_, 1))
println(tuples)
val grouped = tuples.groupBy(_._1)
println(grouped)
val stringToInt = grouped.mapValues(_.size)
println(stringToInt)
val list = stringToInt.toList
println(list)
val sorted = list.sortBy(_._2)
val tuples1 = list.sortWith(_._2 > _._2)
println(sorted)
println(tuples1)
}
}
2、计算以下的数字之和
object Sum {
def main(args: Array[String]): Unit = {
val list = List("1,2,3,4,5","6,7,8","9,10","100")
val strings = list.flatten(_.split(","))
println(strings)
var sum = 0
strings.foreach(sum+=_.toInt)
println(sum)
}
}
3、
1. 创建一个List(3,2,4,6,7,5,1,0,9,8)
2. 将list中每个元素乘以2后生成一个新的集合
3. 将list中的偶数取出来生成一个新的集合
4. 将list排序后生成一个新的集合
5. 反转排序顺序
6. 将list中的元素4个一组方法(grouped),看一下是什么数据类型
7. 将上面方法得到的分组类型转换成List
8. 将多个list压扁成一个List
9. List("hello tom hello jerry", "hello suke hello", " hello tom")
先按空格切分,再压平
object Work3 {
def main(args: Array[String]): Unit = {
val list = List(3,2,4,6,7,5,1,0,9,8)
val list2 = list.map(_ * 2)
println(list2)
val list3 = new ListBuffer[Int]
list.foreach((s)=>{
if(s%2==0)
list3.append(s)
})
println(list3)
val sorted = list.sorted
println(sorted)
val reverse = sorted.reverse
println(reverse)
val iterator = list.grouped(4)
println(iterator)
val list4 = iterator.toList
println(list4)
val flatten = list4.flatten
println(flatten)
val strings = List("hello tom hello jerry", "hello suke hello", " hello tom")
val strings1 = strings.flatMap(_.split(" "))
println(strings1)
}
}