Java 使用动态键获取LinkedHashMapValue

Java 使用动态键获取LinkedHashMapValue,java,groovy,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 ->

我想用动态键从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
。如何使用动态键获取值?

我认为您可以简单地执行以下操作:

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

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

我认为您可以简单地执行以下操作:

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

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

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

keyPath
==“员工1.状态”不是“员工1”。“状态”

因此,要做到这一点,您可以制作如下内容:

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

出于好奇,我试着只使用你的代码

keyPath
==“员工1.状态”不是“员工1”。“状态”

因此,要做到这一点,您可以制作如下内容:

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
可能的重复可能的重复