Reputation: 2702
I have a Map with some calculated values and during reading from Stream, I want to put some of it's (key, values) to this map based on some condition.
How could I achieve it with a brief and concise code?
I'm thinking something like this:
var newcards = scala.collection.mutable.Map[String, String]()
var allCards = scala.collection.mutable.Map[String, String]()
...
newCards.filter(some_condition).append((k:String, v:String) => allCards.put(k, v))
// append method is not present
Upvotes: 0
Views: 401
Reputation: 994
Here's one way to do it with immutable maps. I don't know what your streams look like, but maybe this can be changed to fit your needs:
object Example {
def update[K, V](m: Map[K, V])(s: Stream[(K, V)]): Map[K, V] = s match {
case (k, v) #:: kvs => update(m.updated(k, v))(kvs)
case _ => m
}
def main(args: Array[String]): Unit = {
val s1 = Stream(("b", "2"), ("c", "3"))
val s2 = Stream(("a", "100"))
val m = Map("a" -> "1")
println(update(m)(s1)) //appends
println(update(m)(s2)) //replaces
}
}
Main prints out the following:
Map(a -> 1, b -> 2, c -> 3)
Map(a -> 100)
Upvotes: 2
Reputation: 3250
You don't need to use mutable Map. If you have no other option. Prefer using TrieMap. It is concurrent and will let you modify the Map.
scala> import scala.collection.concurrent.TrieMap
import scala.collection.concurrent.TrieMap
scala> val m1= TrieMap[Int, String](1 -> "I", 2 -> "am", 3 -> "TrieMap", 4 -> "Let", 5 -> "you", 6 -> "modify")
m1: scala.collection.concurrent.TrieMap[Int,String] = TrieMap(1 -> I, 5 -> you, 2 -> am, 6 -> modify, 3 -> TrieMap, 4 -> Let)
scala> val m2= TrieMap[String, String]()
m2: scala.collection.concurrent.TrieMap[String,String] = TrieMap()
scala> m1.filter(_._1 % 2 == 0).foreach {
| case (key, value) => m2(key.toString) = value
| }
scala> m2
res1: scala.collection.concurrent.TrieMap[String,String] = TrieMap(4 -> Let, 2 -> am, 6 -> modify)
Upvotes: 1