阅读 654

Scala中的HashMap

Scala HashMap

HashMap是基于map和哈希的集合。它存储键值对。

表示方式:

    HashMap<Key, Value> or HashMap<K, V>

语法:

    var hashmap = HashMap("key1" -> "value1", ...);

要将HashMap导入我们的Scala程序,请使用以下语句,

    scala.collection.mutable.HashMap

现在,让我们看看Scala中HashMap上的操作,

示例1:在Scala中创建HashMap

在Scala中创建HashMap是一个简单的过程。Scala中的HashMap也可以为空。

import scala.collection.mutable.HashMap 

object MyClass {
    def main(args: Array[String]) {
        var hashmap = new HashMap()
        var hashmap2 = HashMap(1 -> "K1200" , 2 -> "Thunderbird 350", 3 -> "CBR 1000")
        println("Empty HashMap : "+hashmap)
        println("Hashmap with elements : "+hashmap2)
    }
}

输出结果

Empty HashMap : HashMap()Hashmap with elements : HashMap(1 -> K1200, 2 -> Thunderbird 350, 3 -> CBR 1000)

示例2:访问HashMap的元素

可以使用以下所示的foreach循环在Scala中访问HashMap的元素,

import scala.collection.mutable.HashMap 

object MyClass {
    def main(args: Array[String]) {
        var hashmap = HashMap(1 -> "K1200" , 2 -> "Thunderbird 350", 3 -> "CBR 1000")
        hashmap.foreach  
        {   
            case (key, value) => println (key + " -> " + value)          
        }   
    }
}

输出结果

1 -> K12002 -> Thunderbird 3503 -> CBR 1000

示例3:将元素添加到HashMap

也可以使用Scala编程语言将元素添加到HashMap中。在+运算符用于新的键值对添加到HashMap中。

import scala.collection.mutable.HashMap 

object MyClass {
    def main(args: Array[String]) {
        var hashmap = HashMap(1 -> "K1200" , 2 -> "Thunderbird 350", 3 -> "CBR 1000")
        println("The HashMap is : "+hashmap)
        println("Adding new elements to the HashMap. ")
        hashmap += (7 -> "HD Fat Boy")
        println("The HashMap is : "+hashmap)
    }
}

输出结果

The HashMap is : HashMap(1 -> K1200, 2 -> Thunderbird 350, 3 -> CBR 1000)Adding new elements to the HashMap. The HashMap is : HashMap(1 -> K1200, 2 -> Thunderbird 350, 3 -> CBR 1000, 7 -> HD Fat Boy)

示例4:从Scala的HashMap中删除元素

在Scala中,也可以从HashMap中删除元素。的-操作者用来除去从HashMap中的元素。

import scala.collection.mutable.HashMap 

object MyClass {
    def main(args: Array[String]) {
        var hashmap = HashMap(1 -> "K1200" , 2 -> "Thunderbird 350", 3 -> "CBR 1000")
        println("The HashMap is : "+hashmap)
        println("removing elements to the HashMap. ")
        hashmap -= 3        println("The HashMap is : "+hashmap)
    }
}

输出结果

The HashMap is : HashMap(1 -> K1200, 2 -> Thunderbird 350, 3 -> CBR 1000)removing elements to the HashMap. The HashMap is : HashMap(1 -> K1200, 2 -> Thunderbird 350)


文章分类
代码人生
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐