Scala-单词计数程序、并行计算,文件IO(集合常用函数例子)

1、分组


使用grouped(n),每n个为一组,最后不足的略过

scala> val lst3 = lst2.grouped(5)
lst3: Iterator[List[Int]] = non-empty iterator

scala> lst3
res2: Iterator[List[Int]] = non-empty iterator

//将Iterator转为List
scala> val lst4 = lst3.toList
lst4: List[List[Int]] = List(List(1, 2, 3, 4, 5), List(6, 7, 8, 9))

scala> lst4
res3: List[List[Int]] = List(List(1, 2, 3, 4, 5), List(6, 7, 8, 9))

2.最大值和最小值

case class Book(title: String, pages: Int) 
  val books = Seq( Book("Future of Scala developers", 85), 
                  Book("Parallel algorithms", 240), 
                  Book("Object Oriented Programming", 130), 
                  Book("Mobile Development", 495) ) 
  //Book(Mobile Development,495) 
  books.maxBy(book => book.pages) 
  //Book(Future of Scala developers,85) 
  books.minBy(book => book.pages)

3.Euler Diagram 函数

操作就是:差集、交集和并集。以下示例能很好地解释 Euler Diagram 函数:

val num1 = Seq(1, 2, 3, 4, 5, 6)
val num2 = Seq(4, 5, 6, 7, 8, 9)
  
//List(1, 2, 3)
num1.diff(num2)
  
//List(4, 5, 6)
num1.intersect(num2)
  
//List(1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9)
num1.union(num2)

/List(1, 2, 3, 4, 5, 6, 7, 8, 9)
num1.union(num2).distinct

4.对整个集合进行条件检查

有一个场景大家都知道,即确保集合中所有元素都要符合某些要求,如果有哪怕一个元素不符合条件,就需要进行一些处理:而 forall 函数就是为处理这类需求而创建的。

val numbers = Seq(3, 7, 2, 9, 6, 5, 1, 4, 2)
  
//ture
numbers.forall(n => n < 10)
  
//false
numbers.forall(n => n > 5)

//对比记忆map方法
val lst = List(1,4,2,6,7,8)
lst.map(_>5).toBuffer  //ArrayBuffer(false, false, false, true, true, true)

5.对集合进行分组

val numbers = Seq(3, 7, 2, 9, 6, 5, 1, 4, 2)    
//(List(2, 6, 4, 2), List(3, 7, 9, 5, 1))    
numbers.partition(n => n % 2 == 0)

6.wordcount程序编写

package com.day02


/**
  * @Description:
  * @Author: 
  * @Version: V1.0
  * @Since: 1.0
  * @Date 2019/2/13 15:59
  */
object wordCount {

  def main(args: Array[String]): Unit = {
    val lines = List("hello tom jerry", "hello tom take", "hello hello take")

    //统计每个单词的个数
    //1.每一行数据进行切分,得到一个一个的单词list(Array(word1,word2...))
    val words: List[String] = lines.flatMap(_.split(" "))
    // println(words)

    //2.
    val tupleList:List[(String,Int)] = words.map((_,1))
    //val tupleList1:List[(String,Int)] = words.map((x:String) => (x,1))
   // println(tupleList)

    //3.
    //根据tuple的第一个元素进行分组
    val grouped:Map[String,List[(String,Int)]] = tupleList.groupBy(_._1)
    println(grouped)

    //4.
    //聚合,根据key的元素进行聚合
//    for(elem <- grouped)
//      println(elem)
    //mapValues ,对键值对里面的值进行操作,遍历每个value,本例的值是List集合
    //mapValue 每次遍历,拿到的是键值对里面的
    //val maped:Map[String, Int] = grouped.mapValues(_.size)

    //println(maped)
    /**
      * 4.另一种做法
      * 两种修改方案:
      * 1,val maped=grouped.mapValues(_.map(_._2).reduce(_+_))
      * 2,val maped=grouped.mapValues(_.reduce((x,y)=>(x._1,x._2+y._2))).map(_._2)
      */
    //val maped = grouped.map(x => (x._1,x._2.size))
    //val maped = grouped.mapValues(_.map(_._2).reduce(_+_))
    //println("测试1111111")
    //println(grouped.mapValues(_.map(_._2)))
    //println(grouped.mapValues(_.map(_._1)))
    //println(grouped.keys)

    val maped = grouped.mapValues(_.reduce((x,y) => (x._1, x._2+y._2))).map(_._2)
    //println("测试2")
    //println(grouped.mapValues(_.reduce((x,y) => (x._1, x._2+y._2))))
    //println(grouped.mapValues(_.reduce((x,y) => (x._1, x._2+y._2))).map(_._2))


    // map 转化为 list
    val list = maped.toList
    println(list)


    //5.
    //排序
    //val sorted = list.sortWith(_._2 > _._2)
    val sorted = list.sortBy(_._2).reverse
    //list.sortWith((x:(String,Int),y:(String,Int)) => {x._2 > y._2})

    println(sorted)

  }

}

并行计算的一些方法

scala> val a = Array(1,2,3,4,5,6)
a: Array[Int] = Array(1, 2, 3, 4, 5, 6)

scala> a.sum
res41: Int = 21

scala> a.reduce(_+_)  //reduce调的是reduceLeft,从左往右操作
res42: Int = 21

scala> a.reduce(_-_)
res43: Int = -19


scala> a.par //转换为并行化集合
res44: scala.collection.parallel.mutable.ParArray[Int] = ParArray(1, 2, 3, 4, 5, 6)

scala> a.par.reduce(_+_)//会将集合切分为好几块然后并行计算最后汇总
res45: Int = 21

scala> a.fold(10)(_+_)  //先给初始值10,加上a中所有值之和。fold是并行计算,第一个_表示初始值或者累加过后的结果
res46: Int = 31

scala> a.par.fold(10)(_+_) //并行化之后可能就不一样了,每份都要+10
res47: Int = 51

scala> a.par.fold(0)(_+_)
res49: Int = 21

文件I/O

Scala 进行文件写操作,直接用的都是 java中 的 I/O 类 (java.io.File):

import java.io._

object Test {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("test.txt" ))

      writer.write("hello world")
      writer.close()
   }
}

从屏幕读取输入

object Test {
   def main(args: Array[String]) {
      print("请输入你的名字 : " )
      val line = Console.readLine
      
      println("谢谢,你输入的是: " + line)
   }
}

从文件上读取内容
从文件读取内容非常简单。我们可以使用 Scala 的 Source 类及伴生对象来读取文件。

import scala.io.Source

object Test {
   def main(args: Array[String]) {
      println("文件内容为:" )

      Source.fromFile("test.txt" ).foreach{ 
         print 
      }
   }
}
import scala.io.Source

object Test {
   def main(args: Array[String]) {
      println("文件内容为:" )

      Source.fromFile("test.txt" ).getLines.foreach{ 
         print 
      }
   }
}

https://www.jianshu.com/p/0df82acac228

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值