📜  Scala HashMap(1)

📅  最后修改于: 2023-12-03 15:34:49.511000             🧑  作者: Mango

Scala HashMap

Scala HashMap is a collection implementation that maps keys to values. It is a mutable collection, which means that its contents can be changed after it is created. Scala HashMap has a similar interface to Java's HashMap, but it offers many additional features and is optimized for Scala's functional programming model.

Creating a HashMap

To create a new Scala HashMap, you can use the HashMap class and call its constructor:

import scala.collection.mutable.HashMap

val myMap = new HashMap[String, Int]()

In this example, we're creating a HashMap that maps strings to integers. The parentheses after HashMap are necessary to call the class constructor.

Adding and Retrieving Values

Scala HashMap provides several methods for adding and retrieving values from the map. The most commonly used methods are put and get:

myMap.put("one", 1)
myMap.put("two", 2)

val value1 = myMap.get("one")
val value2 = myMap.get("two")
val value3 = myMap.get("three") // returns None

The put method takes two arguments: a key and a value. If the key already exists in the map, the existing value is overwritten with the new value. The get method takes a key and returns an Option that contains the value associated with that key.

Removing Values

To remove a key-value pair from a Scala HashMap, you can use the remove method:

myMap.remove("one")

This method takes a key and removes the key-value pair associated with it.

Iterating Over Keys and Values

Scala HashMap provides several ways to iterate over its keys and values. One common way is to use the foreach method, which applies a function to each key-value pair in the map:

myMap.foreach { case (key, value) => 
  println(s"key: $key, value: $value")
}

This code will print:

key: two, value: 2

Another way to iterate over the keys or values is to use the keys or values methods:

val keys = myMap.keys
val values = myMap.values

These methods return iterable collections of the keys or values in the map.

Conclusion

Scala HashMap is a powerful collection that provides an easy way to map keys to values. It has many convenient methods for adding, retrieving, and removing values, as well as for iterating over the keys and values in the map. By using Scala HashMap, you can write clean and concise code that is optimized for Scala's functional programming model.