Scala应用

求字符串中单词出现次数val arr = Array(“hello tom”,“hello jerry”,“hello hello”)

    //1.先将每一个字符串分割
    var f4 = (x:String)=>x.split("\\s")
    //2.分割出的结果为Array(Array(hello,tom),Array(hello,jerry),Array(hello,hello))
    var arr1 = arr.map(f4)
    //3.将数组平铺
    var f5 = (x:Array[String]) => List(x(0),x(1))
    //4.平铺的结果为List(hello,tom,hello,jerry,hello,hello)
    var arr2 = arr1.flatMap(f5)
    //5.将集合中的每一个元素转换格式
    //6.转换结果为
    // List((hello,1),(tom,1),(hello,1),(jerry,1),(hello,1),(hello,1))
    var arr3 = arr2.map(x=>(x,1))
    //7.将集合中的元组分组,结果为
    //Map(tom -> [Lscala.Tuple2;@62ee68d8, jerry -> [Lscala.Tuple2;@735b5592, hello -> [Lscala.Tuple2;@58651fd0)
    //Map(tom -> ((tom,1)), jerry -> ((jerry,1)), hello -> ((hello,1),(hello,1),(hello,1),(hello,1)))
    var arr4 = arr3.groupBy(_._1)
    println(arr4)
    //8.显示最终结果
    var arr5 = arr4.map(x=>(x._1,x._2.length))
    println(arr5)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值