Michael
Michael

Reputation: 10303

Simple Scala coding question

Suppose I have list countries of type List[String] and map capitals of type Map[String, String]. Now I would like to write a function

pairs(countries:List[String], capitals:Map[String, String]):Seq[(String, String)]
to return a sequence of pairs (country, capital) and print an error if the capital for some country is not found. What is the best way to do that?

Upvotes: 1

Views: 205

Answers (2)

Dave Griffith
Dave Griffith

Reputation: 20515

countries.map(x=>(x, capitals(x)))

Upvotes: 9

Kevin Wright
Kevin Wright

Reputation: 49705

To start with, your Map[String,String] is already a Seq[(String,String)], you can formalise this a bit by calling toSeq if you wish:

val xs = Map("UK" -> "London", "France" -> "Paris")
xs.toSeq
// yields a Seq[(String, String)]

So the problem then boils down to finding countries that aren't in the map. You have two ways of getting a collection of those countries that are represented.

The keys method will return an Iterator[String], whilst keySet will return a Set[String]. Let's favour the latter:

val countriesWithCapitals = xs.keySet
val allCountries = List("France", "UK", "Italy")
val countriesWithoutCapitals = allCountries.toSet -- countriesWithCapitals
//yields Set("Italy")

Convert that into an error in whatever way you see fit.

Upvotes: 10

Related Questions