《快学Scala》第四章练习题答案+概述

第四章

1、内容概述

  • 4.1 构造映射 & 4.2 获取映射

    //定义
    var map = Map("one" -> 1 , "two" -> 2 , "three" -> 3)
    var map = Map(("one" , 1 ), )("two", 2) , ("three", 3))
    //获取
    map("one")    
    //如果映射中不包括指定的键,可以先判断
    val res = if(map.contains("on")) map("on") else 0   // res = 0
    //还可以这样
    val res = map.getOrEles("one" , 0)    
    //在java中也有这样的操作
    
  • 4.3 更新映射中的值

    map("one") = 10 //更新 one 对应的值
    map("two") = 20 //更新 two 对应的值
    //添加    
    map += ("four" -> 4 , "five" -> 5)    
    //删除
    map - = "one"    
    
  • 4.4 迭代映射

    //迭代
    for((k,v) <- map) println(k +" :" + v) 
    //获取所有的key
    map.keySet
    //获取所有的value
    map.values 
    //反转
    for((k,v) <- map) yield(v,k)  
    
  • 4.5 已排序映射

    scala默认的是哈希表  
    //树形映射
    val scores = scala.collections.immutable.SortedMap("one" -> 1 , "two" -> 2 , "three" -> 3)
    //有序 -根据插入顺序
    val scores = scala.collection.mutable.LinkedHashMap("one" -> 1 , "two" -> 2 , "three" -> 3)    
    
  • 4.6 Java互操作

    // Scala到Java的转换
    import scala.collection.JavaConversions.mapAsScalaMap
    // 1.通过Scala映射类型触发转换
    val scores:scala.collection.mutable.Map[String,Int] = new java.util.TreeMap[String,Int]
    // 2.得到转换
    import scala.collection.JavaConversions.propertiesAsScalaMap
    val props:scala.collection.Map[String,String] = System.getProperties()
    //java到Scala的转换
    import scala.collection.JavaConversions.mapAsJavaMap
    import java.awt.font.TextAttribute._
    val x = Map("one" -> 1 , "two" -> 2 , "three" -> 3)
    val y = new java.awt.Font(x)    
    
    
  • 4.7 元组

    //不同类型的值的聚集 各组元从1开始
    var a =1,20.12, "wod"//获取
    val two = a._2 
    
    //定义
    Tuple2[Int , Int]
    Tuple3[Int , Int , Int]
    Tuple4[Int , Int , Int , Int]
    
  • 4.8 拉链操作

    多个值进行绑定
    val x = Array("<" ,"-",">")
    val y = Array(2, 3 ,4)
    val xy = x.zip(y)    //(("<",2),("-", 3),(">" , 4))
        
    
    

2、习题

  • 4.1 设计1个映射,其中包含你需要的一些装备,以及他们的价格然后构建另一组映射,采用同样的键,但在价格上打九折
    def problem_1(): Unit = {
        val m1 = Map[String, Double]("如意金箍棒" -> 15000.23, "九齿钉耙" -> 500.48, "降魔杖" -> 200.51)
        //定义可变映射
        val m2 = mutable.HashMap[String, Double]()
        //添加数据
        for ((key, value) <- m1) m2(key) = value * 0.9
        //查看结果
        for ((key, value) <- m2) print(key + ":" + value + " ")
    
        m2.foreach(x => println(x))
    
      }
    
  • 4.2 编写一段程序,从文件中读取单词;用一个可变的映射清点单词出现的频率
    def problem_2(): Unit = {
        //创建可变映射
        val m1 = mutable.HashMap[String, Int]()
        //读取文件
        val file = Source.fromFile(path)
        file.getLines().foreach(
          line => {
            for (w <- line.split(" ")) {
              if (m1.contains(w)) {
                m1(w) = m1(w) + 1
              } else {
                m1(w) = 1
              }
            }
          }
        )
    
        for ((k, v) <- m1) printf("word:%s,count:%d\n", k, v)
      }
    
  • 4.3重复做前一个练习,这次用不可变映射
     def problem_3(): Unit = {
        var m1 = Map[String, Int]()
        val file = Source.fromFile(path)
        file.getLines().foreach(line => {
          for (w <- line.split(" ")) {
            var newM1: Map[String, Int] = null
            if (m1.contains(w)) {
              val x = m1(w) + 1;
              newM1 = m1 + (w -> x)
            } else {
              newM1 = m1 + (w -> 1)
            }
            m1 = newM1
          }
        })
        for ((k, v) <- m1) printf("Word:%s , count:%d \n", k, v)
      }
    
  • 4.4 重复前一个练习,这次用排序集合,使得单词可以以排序的方式输出
    def problem_4(): Unit = {
        var m1 = SortedMap[String, Int]()
        val file = Source.fromFile(path)
        file.getLines().foreach(line => {
          for (w <- line.split(" ")) {
            var newM1: SortedMap[String, Int] = null
            if (m1.contains(w)) {
              val x = m1(w) + 1;
              newM1 = m1 + (w -> x)
            } else {
              newM1 = m1 + (w -> 1)
            }
            m1 = newM1
          }
        })
        for((k,v) <- m1) printf("word:%s ,count:%d\n", k,v)
    
      }
    
  • 4.5 重复前一个练习,这次用java.util.TreeMap,并使其适用于scala
    def problem_5(filepath: String): Unit = {
        val countMap = new util.TreeMap[String, Int]()
        Source.fromFile(filepath).getLines().foreach(
          line => {
            for (word <- line.split(" ")) {
              if (!countMap.keySet().contains(word.toLowerCase)) countMap(word.toLowerCase) = 0
              countMap(word.toLowerCase) = countMap(word.toLowerCase) + 1
            }
          }
        )
    
        for ((word, wordcount) <- countMap) {
          printf("word:%s,count:%d\n", word, wordcount)
        }
      }
    
  • 4.6 定义一个链式哈希映射,将“Monday”映射到java.util.Calendar.MONDAY,依次类推假如其他日期,展示元素是以插入的顺序被访问的
    def problem_6(): Unit ={
        val map = mutable.LinkedHashMap[String ,Int]()
        map += ("MONDAY" -> Calendar.MONDAY)
        map += ("TUESDAY" -> Calendar.TUESDAY)
        map += ("WEDNESDAY" -> Calendar.WEDNESDAY)
        map += ("THURSDAY" -> Calendar.THURSDAY)
        map += ("FRIDAY" -> Calendar.FRIDAY)
        map += ("SATURDAY" -> Calendar.SATURDAY)
        map += ("SUNDAY" -> Calendar.SUNDAY)
        println(map.toBuffer)
      }
    
  • 4.7 打印java系统属性表格
     def problem_7(): Unit = {
        val sysmap = System.getProperties
        var maxlen: Int = 0
        for ((key, value) <- sysmap if String.valueOf(key).length > maxlen) maxlen = String.valueOf(key).length
        for ((key, value) <- sysmap) println(key + " " * (maxlen - String.valueOf(key).length) + "|" + value)
      }
    
  • 4.8 编写一个函数minmax(values:Array[Int]),返回数组中最大值和最小值的对偶
    def minmax(values: Array[Int]): Tuple2[Int, Int] = {
        Tuple2[Int, Int](values.min, values.max)
    }
    
  • 4.9 编写一个函数lteqgt(values:Array[Int],v:Int),返回数组中小于v,等于v和大于v的数量要求一起返回
    def lteqgt(values: Array[Int], v: Int): Tuple3[Int, Int, Int] = {
        var lcount = 0
        var ecount = 0
        var gcount = 0
        for (elem <- values) {
          if (elem < v) {
            lcount = lcount + 1
          } else if (elem == v) {
            ecount = ecount + 1
          } else {
            gcount = gcount + 1
          }
        }
        Tuple3[Int, Int, Int](lcount, ecount, gcount)
      }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值