使用动态密钥获取LinkedHashMapValue

时间:2018-07-10 10:17:51

标签: java groovy

我想使用如下所示的动态键从LinkedHashmap中获取值。

def map = [Employee1: [Status: 'Working', Id: 1], Employee2:  [Status: 'Resigned', Id: 2]]

def keys = "Employee1.Status"
def keyPath = "";
def keyList = keys.tokenize(".");


keyList.eachWithIndex() { key, i ->

    keyPath += "$key"

    if(i != keyList.size() - 1){   keyPath += "."     } 
}

println keyPath //Employee1.Status
println map.keyPath //Always null
println map.'Employee1'.'Status' //Working
println map.Employee1.Status //Working

这里map.keyPath总是返回null。如何通过动态键获取值?

2 个答案:

答案 0 :(得分:2)

我认为您可以简单地做到这一点:

def tmpMap = map;
keyList.subList(0, keyList.size - 1).each {key -> 
   tmpMap = map[key]    
}
println tmpMap[keyList[keyList.size - 1]]

这将提取子图,直到达到实际值键为止。为了使它更稳定,您应该添加一些逻辑以检查与当前键关联的值是否实际上是一个映射。

答案 1 :(得分:2)

出于好奇,我尝试仅使用您的代码。

keyPath =='Employee1.Status'而不是'Employee1'。'Status'

因此,您可以执行以下操作:

def map = [
    Employee1: 
    [Status: 'Working', Id: 1], 
    Employee2:  
    [Status: 'Resigned', Id: 2]
    ]

def keys = "Employee1.Status"
def keyPath = "";
def keyList = keys.tokenize(".");



keyList.eachWithIndex() { key, i ->

    keyPath += "$key"
    if(i != keyList.size() - 1){   keyPath += '.'     } 

}

println keyPath //Employee1.Status
//tokenize it and get elements as a[0] and a[1]
a = keyPath.tokenize(".");
println map.(a[0]).(a[1]) //Working
println map.'Employee1'.'Status' //Working
println map.Employee1.Status //Working