假设我有类型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 - 我正在从描述中工作:“如果某个国家的首都没有找到,打印一个错误” –