Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Comment

HashTable is a trait without a factory method and thus cannot be instantiated. HashMap and HashSet are subclasses that you should use.

https://stackoverflow.com/questions/3648870/scala-using-hashmap-with-a-default-value

import collection.immutable.HashMap

val m = HashMap("x" -> 24, "y" -> 25)
m
m = Map(x -> 24, y -> 25)
Map(x -> 24, y -> 25)
m("x")
24
for ((k,v) <- m) {
    println(k + ": " + v)
}
x: 24
y: 25
m.foreach {
    e => println(e._1 + ": " + e._2)
}
x: 24
y: 25
m.isInstanceOf[Map[String, Int]]
true
val m = Map("x1" -> 24, "x2" -> 24)
m.isInstanceOf[HashMap[String, Int]]
false
val m = Map("x1" -> 24, "x2" -> 24, "x3" -> 100, "x4" -> 200, "x5" -> 300)
m.isInstanceOf[HashMap[String, Int]]
true
m.getClass
class scala.collection.immutable.HashMap$HashTrieMap

toMap

List(("Ben", 1), ("Lisa", 2)).toMap
Map(Ben -> 1, Lisa -> 2)
List(("Ben", 1), ("Lisa", 2)).toMap
Map(Ben -> 1, Lisa -> 2)

Seq of Tuple to Map

Seq(("Ben", 30), ("Dan", 40), ("Kun", 34)).toMap
Loading...

Notice that if a key appears more than once, the last occurrence is used.

Seq(("Ben", 30), ("Dan", 40), ("Dan", 34), ("Ben", 20)).toMap
Loading...

You can manually define the behavior of aggregation of course. For example, the code below sum values belong to the same key.

Seq(
    ("Ben", 30),
    ("Dan", 40),
    ("Dan", 34),
    ("Ben", 20)
).groupBy(_._1).mapValues{
    values => {
        values.map(_._2).sum
    }
}
Loading...

Count Frequencies of Values

Seq(1, 1, 2, 2, 3, 1, 2, 2, 4, 3).groupBy(identity).mapValues(_.size)
Loading...

Iterate a Map

import collection.immutable.HashMap

val m = HashMap("x" -> "24", "y" -> "25")
m
Loading...
val sql = "select * from table where id in (${x}, ${y})"
select * from table where id in (${x}, ${y})
m.foldLeft(sql)((res, item) => res.replaceAllLiterally("${" + item._1 + "}", item._2))
select * from table where id in (24, 25)

Join Lists

val l1 = List(
    ("Ben", 1.0),
    ("Lisa", 2.0)
)

val l2 = List(
    ("Ben", 1000.0),
    ("Tiger", 2000.0)
)
[[(Ben,1000.0), (Tiger,2000.0)]]
def join(c1: List[(String, Double)], c2: List[(String, Double)]): List[(Double, Double)] = {
    val m = c2.toMap
    c1.collect {
      case (user, toc) if m.contains(user) => (toc, m(user))
    }
}
join: (c1: List[(String, Double)], c2: List[(String, Double)])List[(Double, Double)]
join(l1, l2)
[[(1.0,1000.0)]]