1

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?

0

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Are you assuming that the list of countries is a superset of the keys of the map? The primary goal might be to present the capitals of a small list of countries, rather than to find missing countries in the Map. It's not completely clear from the question, though.
@Ben - I'm working from the description: "print a error if the capital for some country is not found"
9
countries.map(x=>(x, capitals(x)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.