Scala:获取 Map.head 元素的键(和值)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9778405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala: getting the key (and value) of a Map.head element
提问by Blackbird
Let's imagine the following immutable Map:
让我们想象一下下面的不可变 Map:
val foo = Map((10,"ten"), (100,"one hundred"))
I want to get the key of the first element.
我想获取第一个元素的键。
foo.headgets the first element. But what next?
foo.head获取第一个元素。但是接下来呢?
I also want the value of this element, i.e. "ten"
我也想要这个元素的值,即“十”
回答by IODEV
Set a key/value pair:val (key, value) = foo.head
设置键/值对:val (key, value) = foo.head
回答by Paolo Falabella
Map.head returns a tuple, so you can use _1 and _2 to get its index and value.
Map.head 返回一个元组,因此您可以使用 _1 和 _2 来获取其索引和值。
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

