Blackbird
Blackbird

Reputation: 2378

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"

Upvotes: 17

Views: 28463

Answers (3)

Alessandro Cinque
Alessandro Cinque

Reputation: 43

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.

Upvotes: 1

IODEV
IODEV

Reputation: 1735

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

Upvotes: 29

Paolo Falabella
Paolo Falabella

Reputation: 25844

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

Upvotes: 23

Related Questions