Finding the key in a map, given the value

前端 未结 5 2522
迷失自我
迷失自我 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.

    0 讨论(0)
  • 2021-02-20 17:30

    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']
    
    0 讨论(0)
  • 2021-02-20 17:32

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

    0 讨论(0)
  • 2021-02-20 17:33
    def expect = 5
    def m = ['this':0, is:1, a:2, file:3,  aa:5]
    def r = m.collectMany{ k,v -> (v == expect) ? [k] : []}
    
    // Result: [aa]
    
    0 讨论(0)
  • 2021-02-20 17:35

    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'
    
    0 讨论(0)
提交回复
热议问题