Finding the key in a map, given the value

前端 未结 5 2659
迷失自我
迷失自我 2021-02-20 16:57

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

5条回答
  •  生来不讨喜
    2021-02-20 17:19

    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.

提交回复
热议问题