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

24,345

Solution 1

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

Solution 2

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

Solution 3

I must say that @Paolo Falabella had the best answer, as using

val (key, value) = foo.head

in a tail-recursive method will lead to a crash!

So it is much better/more versatile to use

val myMap = Map("Hello" ->"world", "Hi" -> "Everybody")
print(myMap.head._1)

which would print "Hello" and won't cause a crash in a tails recursive method.

Share:
24,345
Blackbird
Author by

Blackbird

Updated on July 09, 2022

Comments

  • Blackbird
    Blackbird almost 2 years

    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"

    • leedm777
      leedm777 about 12 years
      Maps aren't sorted. So 'first' isn't always what you think it is. Just keep that in mind :-)
  • Blackbird
    Blackbird about 12 years
    Thanks for the detailed answer. IODEV's solution looks very nice I must say.
  • Ajay Sant
    Ajay Sant over 6 years
    Is there a way to get the top 2 (key, value) pairs or top 3 instead of only the first.