在给定值的情况下查找地图中的关键字 [英] Finding the key in a map, given the value

查看:116
本文介绍了在给定值的情况下查找地图中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有这样的地图:

  [this:0,is:1,a:2,file: 3,anotherkey:4,aa:5] 

我希望能找到 key 给出地图的。例如,如果给定值 5 ,我需要从地图返回 aa



是否有可能?

解决方案

我不知道是否有直接的方法可以获得一个给定值的关键字,但使用 Map#find 得到一个map条目,然后得到它的值应该足够了:

  def keyForValue(map,value){
map.find {it.value == value} ?. key
}

def map = [a: 1,b:2,c:3]
assert keyForValue(map,2)=='b'
assert keyForValue(map,42)== null

一般而言,地图不需要在其条目之间存在顺序关系,但Groovy文字地图的默认实现是LinkedHashMap,它 是有序的,所以当使用这些映射时, keyForValue 总会产生一个值的第一个键s。

Hi I have a map like this :

[this:0, is:1, a:2, file:3, anotherkey:4, aa:5]

I wish I could find the key's given the value of a map. For example, if the value 5 is given I need to return aa from the map.

Is that possible?

解决方案

I don't know if there's a direct method to get a key for a given value, but using Map#find to get a map entry and then get its value should be enough:

def keyForValue(map, value) {
    map.find { it.value == value }?.key
}

def map = [a: 1, b: 2, c: 3]
assert keyForValue(map, 2) == 'b'
assert keyForValue(map, 42) == null

In general, maps don't need to have an order relation between their entries, but the default implementation for Groovy's literal maps is LinkedHashMap, which is ordered, so the keyForValue will always yield the first key for a value when using those maps.

这篇关于在给定值的情况下查找地图中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆