Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: getting the key (and value) of a Map.head element

Let's imagine the following immutable Map:

val foo = Map((10,"ten"), (100,"one hundred"))

I want to get the key of the first element.

foo.head gets the first element. But what next?

I also want the value of this element, i.e. "ten"

like image 684
Blackbird Avatar asked Mar 19 '12 21:03

Blackbird


2 Answers

Set a key/value pair:
val (key, value) = foo.head

like image 164
IODEV Avatar answered Oct 23 '22 06:10

IODEV


Map.head returns a tuple, so you can use _1 and _2 to get its index and value.

scala> val foo = Map((10,"ten"), (100,"one hundred"))
foo: scala.collection.immutable.Map[Int,java.lang.String] = Map(10 -> ten, 100 -
> one hundred)

scala> val hd=foo.head
hd: (Int, java.lang.String) = (10,ten)

scala> hd._1
res0: Int = 10

scala> hd._2
res1: java.lang.String = ten
like image 24
Paolo Falabella Avatar answered Oct 23 '22 06:10

Paolo Falabella