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://
import collection.immutable.HashMap
val m = HashMap("x" -> 24, "y" -> 25)
mm = Map(x -> 24, y -> 25)
Map(x -> 24, y -> 25)m("x")24for ((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]]trueval m = Map("x1" -> 24, "x2" -> 24)
m.isInstanceOf[HashMap[String, Int]]falseval m = Map("x1" -> 24, "x2" -> 24, "x3" -> 100, "x4" -> 200, "x5" -> 300)
m.isInstanceOf[HashMap[String, Int]]truem.getClassclass scala.collection.immutable.HashMap$HashTrieMaptoMap¶
List(("Ben", 1), ("Lisa", 2)).toMapMap(Ben -> 1, Lisa -> 2)List(("Ben", 1), ("Lisa", 2)).toMapMap(Ben -> 1, Lisa -> 2)Seq of Tuple to Map¶
Seq(("Ben", 30), ("Dan", 40), ("Kun", 34)).toMapLoading...
Notice that if a key appears more than once, the last occurrence is used.
Seq(("Ben", 30), ("Dan", 40), ("Dan", 34), ("Ben", 20)).toMapLoading...
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")
mLoading...
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)]]