Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the key in a map, given the value

Tags:

map

groovy

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?

like image 325
sriram Avatar asked Dec 26 '12 18:12

sriram


4 Answers

There's no specific command for that.

Fortunately, as showed here, you can easily get the key(s) for a specific value in a map:

def myMap = [this:0, is:1, a:2, file:3, fix:4, aa:5]
def myValue = 5

You can do:

def myKey = myMap.find{ it.value == myValue }?.key
// 'aa'

If you want all the keys, do something like this:

def myMap = [this:0, is:1, a:2, file:3, fix:4, aa:5, bb:5]
def myValue = 5

def myKeys = []
myMap.findAll{ it.value == myValue }.each{myKeys << it?.key}
// ['aa', 'bb']
like image 107
lucke84 Avatar answered Oct 22 '22 06:10

lucke84


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.

like image 42
epidemian Avatar answered Oct 22 '22 06:10

epidemian


You could invert the map, like this:

Map m = [a: '1', b: '2']
Map mInvert = m.collectEntries { e -> [(e.value): e.key] }

assert mInvert == ['1':'a', '2':'b']

assert mInvert['2'] == 'b'
assert m['b'] == '2'
like image 24
crazy4groovy Avatar answered Oct 22 '22 07:10

crazy4groovy


You'll probably have to iterate over the entry set yourself and try to find the entry with a matching value.

like image 27
JimmyB Avatar answered Oct 22 '22 06:10

JimmyB