我有一个元组
ffc00000
我需要一个函数来转换上面映射的字符串的第三个字母
示例:
{("ABC", "123"),("DEF", "456"),("GHI", "789")}
我该怎么做?我是Scala编程的新手,希望在此提供任何帮助。
答案 0 :(得分:1)
假设您有一个元组列表
val listOfTuples = List(
("ABC", 123),
("DEF", 456),
("GHI", 789),
)
现在要将其转换为地图,您可以编写以下函数
val endOfMap = "ADF_MESSAGE" + (listOfTuples.size + 1)
listOfTuples.zipWithIndex.map {
case ((str, int), index) =>
(str.take(3) + "_MESSAGE" + (index + 1)) -> (int + "_MESSAGE" + (index + 1))
}.toMap + (endOfMap -> endOfMap)
这将为您获取输出
res0: scala.collection.immutable.Map[String,String] = Map(ABC_MESSAGE1 -> 123_MESSAGE1, DEF_MESSAGE2 -> 456_MESSAGE2, GHI_MESSAGE3 -> 789_MESSAGE3, ADF_MESSAGE4 -> ADF_MESSAGE4)
答案 1 :(得分:1)
将元组变成Map
以便于查找。
val lookup = Seq(("ABC","123"), ("DEF","456"), ("GHI","789")).toMap
Seq("ABC_MESSAGE1", "DEF_MESSAGE2", "GHI_MESSAGE3", "ADF_MESSAGE4")
.map(msg =>lookup.get(msg.take(3)).fold(msg)(_ + msg.drop(3)))
//res0: Seq[String] = List(123_MESSAGE1, 456_MESSAGE2, 789_MESSAGE3, ADF_MESSAGE4)