Finding the key in a map, given the value

前端 未结 5 2654
迷失自我
迷失自我 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: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']
    

提交回复
热议问题