scala中Map映射

文章目录

      • 1.映射的创建(3种)
      • 2.获取映射中的值
      • 2.更新映射中的值

       业内有这样一句话:“如果世界上只能有一种数据结构,那就用哈希表吧”,哈希表——更笼统地说——映射,映射是键/值对偶的集合,也有个通用的而叫法——元祖:n个对象的集合,不一定是同一种类型。

1.映射的创建(3种)

  
    //不可变映射
    val map= Map("name"->"Tom","age"->15)
    println(map("name"))

    //可变映射
    val user = scala.collection.mutable.Map("name"->"Alience","age"->15)
    //更改
    user.update("name","Susan")
    print(user("name"))
    
    //创建一个空的映射,事先给出参数类型,然后赋值
    val hashMap = new mutable.HashMap[String,String]()
    hashMap("hobby")="eat"
    hashMap.put("name","Aack")
    hashMap += ("dream"->"riching","friend"->"Tom")
    print(hashMap)
    
run:-----------------------
	Tom
	
	(性别0,年龄15)
	
	Susan
	
	Map(dream -> riching, hobby -> eat, friend -> Tom, name -> Aack)

2.获取映射中的值

    val hashMap = new mutable.HashMap[String,String]()
    hashMap("hobby")="eat"
    hashMap.put("name","Aack")
 
    //获取键hobby的值
    val hobby = hashMap("hobby")
    
    //如果映射种没有请求中的键,则会报异常
    //val weight = hashMap("weight")
    
    //使用contains方法检查是否含有指定的键
    val weight = if (hashMap.contains("weight"))hashMap("weight") else 0
    
    //判断取值的快捷方法getOrElse(Object,Object)
    val hobby2 = hashMap.getOrElse("hobby","fight")
    
    //判断更新取值的getOrElseUpdate(Object,Object),有键则取值,无键则添加映射并取值
    val friend = hashMap.getOrElseUpdate("friend","Bash")
    
    print(hobby,weight,hobby2,friend)

-run:----------------------------------------
	(eat,0,eat,Bash)
	

2.更新映射中的值

    val hashMap = new mutable.HashMap[String,String]()
    hashMap("hobby")="eat"
    //更改"hobby",并且添加name
    hashMap += ("hobby"->"talk","name"->"Tom")
    print(hashMap)
    
    //减去hobby
    hashMap-="hobby"
    print(hashMap)
    
run:-------------------------------
Map(hobby -> talk, name -> Tom)
Map(name -> Tom)

你可能感兴趣的:(scala)