Suppose you have your keys in a list like this, and you want to convert it with squares as values.
scala> val keyList = ( 1 to 10 ).toList keyList: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> val doSquare = ( x: Int ) => x * x doSquare: Int => Int = <function1> // Convert it to the list of tuples - ( key, doSquare( key ) ) scala> val tupleList = keyList.map( key => ( key, doSquare( key ) ) ) tuple: List[(Int, Int)] = List((1,1), (2,4), (3,9), (4,16), (5,25), (6,36), (7,49), (8,64), (9,81), (10,100)) val keyMap = tuple.toMap keyMap: scala.collection.immutable.Map[Int,Int] = Map(5 -> 25, 10 -> 100, 1 -> 1, 6 -> 36, 9 -> 81, 2 -> 4, 7 -> 49, 3 -> 9, 8 -> 64, 4 -> 16)
Or do it in one line
( 1 to 10 ).toList.map( x => ( x, x * x ) ).toMap
Or ... if you have only a few keys ... then you can write specific code
Map( 1 -> doSquare( 1 ), 2 -> doSquare( 2 ) )