mongolol mongolol - 1 year ago 93
Scala Question

Treating an Array of (String, Int) Tuples like a Dictionary

I have a list of tuples that looks like the following:

(("String1", Value1), ("String2", Value2), ...)

Where string is a
and value is a
. Is there a method in scala to accomplish the following:

1) Search the list for a particular string value.

2) If we have a hit, return the value associated with the string.

3) If we have a miss, return -1.

This tuple sequence was created using
on an RDD of format RDD[K, V] where the keys were strings and the vals were the doubles. Originally I planned on using lookup on the RDD, but it appears that this work needs to be done on the driver (hence the

Answer Source

Maybe you can try to convert it to a map first then:

scala> val collection = Map(("hello", 1), ("world", 2))
collection: scala.collection.immutable.Map[String,Int] = Map(hello -> 1, world -> 2)

scala> collection getOrElse ("hello", -1)
res3: Int = 1

scala> collection getOrElse ("scala", -1)
res4: Int = -1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download