在 Scala 中对地图使用 find 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19572600/
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
Using find function for maps in scala
提问by Core_Dumped
I am trying to find a key in a Map, given a value. I am using the 'find' function by not able to figure out the right predicate for it:
我试图在地图中找到一个键,给定一个值。我使用 'find' 函数时无法找出正确的谓词:
val colors = Map(1 -> "red", 2 -> "blue")
def keyForValue(map: Map[Int, String], value: String) = {
val bool = map.find{map.foreach{map.values(i) == value}}
bool.key
}
How do I iterate over the map and find the key when I know the value?
当我知道值时,如何遍历地图并找到键?
回答by miko?ak
You use the same kind of predicate as with a List, but keep in mind you're evaluating it over (key,value)pairs, instead of just values (and getting a pair back as well!).
您可以使用同一种谓词与一个List,但记住你评估过来(key,value)对,而不是只值(并得到一双回来的!) 。
Simple example:
简单的例子:
val default = (-1,"")
val value = "red"
colors.find(_._2==value).getOrElse(default)._1
回答by Brian
The signature for findin Mapis find(p: ((A, B)) ? Boolean): Option[(A, B)]. So the predicate takes a Tuple2and must return a Boolean. Note I changed valueto an Intsince the key in colorsis also an Int.
findin的签名Map是find(p: ((A, B)) ? Boolean): Option[(A, B)]。所以谓词需要 aTuple2并且必须返回 a Boolean。请注意,我更改value为 an,Int因为输入的键colors也是Int.
scala> def keyForValue(map: Map[Int, String], value: Int) = {
| colors.find({case (a,b) => a == value})
| }
keyForValue: (map: Map[Int,String], value: Int)Option[(Int, String)]
Test:
测试:
scala> keyForValue(colors, 1)
res0: Option[(Int, String)] = Some((1,red))
You can also use get:
您还可以使用get:
scala> colors.get(1)
res1: Option[String] = Some(red)
回答by kungfushark
You can always go with the abstract solution and swap the keys with their values, store it in a new map, and then search the new map:
您始终可以使用抽象解决方案并将键与其值交换,将其存储在新映射中,然后搜索新映射:
val colors = Map(1 -> "red", 2 -> "blue")
def keyForValue(map: Map[Int, String], value: String) = {
val revMap = map map {_.swap}
val key = revMap(value)
key
}
The third line swaps the keys with their values, and stores it in revMap. (map mapmeans the name of the map, in this case, the parameter, map, then the word map, then {_.swap}to actually swap the keys with their values.
第三行将键与其值交换,并将其存储在revMap. (map map表示映射的名称,在这种情况下,是参数映射,然后是单词映射,然后{_.swap}实际将键与其值交换。
回答by warrens
I would avoid passing the map to the find method, and rather pass only the map's keysto the find method.
我会避免将地图传递给 find 方法,而是只将地图的键传递给 find 方法。
This avoids dealing with an Option[Int,String]-- instead it is Option[Int].
这避免了处理Option[Int,String]- 而是Option[Int]。
// sample data
val colors = Map(1 -> "red", 2 -> "blue", 3 -> "yellow")
// function you need
def keyForValue(theMap: Map[Int, String], theValue: String): Int = {
val someKey = theMap.keys.find( k => theMap(k) == theValue )
someKey match {
case Some(key) => {
println(s"the map contains ${key} -> ${theValue}")
return key
}
case None => {
println(s"a key was not found for ${theValue}")
return -1
}
}
}
This gives:
这给出:
scala> val result = keyForValue( colors, "blue" )
the map contains 2 -> blue
result: Int = 2
scala>

