假設我有類型List[String]
的列表countries
和類型Map[String, String]
的地圖capitals
。現在我想寫一個函數簡單斯卡拉編碼問題
pairs(countries:List[String], capitals:Map[String, String]):Seq[(String, String)]來返回一系列配對
(country, capital)
,如果沒有找到某個國家的首都,就會打印一個錯誤。什麼是最好的方式來做到這一點?
假設我有類型List[String]
的列表countries
和類型Map[String, String]
的地圖capitals
。現在我想寫一個函數簡單斯卡拉編碼問題
pairs(countries:List[String], capitals:Map[String, String]):Seq[(String, String)]來返回一系列配對
(country, capital)
,如果沒有找到某個國家的首都,就會打印一個錯誤。什麼是最好的方式來做到這一點?
首先,你Map[String,String]
是已經一個Seq[(String,String)]
,您可以通過調用toSeq
形式化一點,如果你想:
val xs = Map("UK" -> "London", "France" -> "Paris")
xs.toSeq
// yields a Seq[(String, String)]
所以,問題則歸結爲尋求國家的不在地圖中。您有兩種方法可以獲得代表爲的國家/地區的集合。
keys
方法將返回Iterator[String]
,而keySet
將返回Set[String]
。讓我們傾向後者:
val countriesWithCapitals = xs.keySet
val allCountries = List("France", "UK", "Italy")
val countriesWithoutCapitals = allCountries.toSet -- countriesWithCapitals
//yields Set("Italy")
將它轉換爲任何您認爲合適的方式的錯誤。
countries.map(x=>(x, capitals(x)))
您是否假設國家列表是地圖鍵的超集?主要目標可能是提供一小部分國家的首都,而不是在地圖中找到失蹤國家。不過,這個問題並不完全清楚。 –
@Ben - 我正在從描述中工作:「如果某個國家的首都沒有找到,打印一個錯誤」 –