gpt4 book ai didi

java - 如何使用 for 循环使用键集迭代 HashMap

转载 作者:行者123 更新时间:2023-12-01 10:19:42 24 4
gpt4 key购买 nike

我正在尝试使用键集检索 Employee 和 Department 表。我的 HashMap 中有 jsonObject。如何使用 for 循环迭代 Employee.employeeId。任何人都可以帮我吗...

我的 simple.json:

{
"routings": {
"routing1": {
"targetCollection-name": "EmployeeData",
"sourcetables-data": {
"Employee": [{
"name": "employeeId",
"sourceDataType": "number",
"targetField": "employeeId",
"targetDataType": "double"
}, {
"name": "firstName",
"sourceDataType": "varchar2",
"targetField": "firstName",
"targetDataType": "string"
}, {
"name": "lastName",
" sourceDataType": "varchar2",
"targetField": "lastName",
"targetDataType": "string"
}, {
"name": "contactNumber1",
"sourceDataType": "number",
"targetField": "contactNumbers",
"targetDataType": "array"
}],
"department": [{
"name": "departmentNumber",
"sourceDataType": "number",
"targetField": "departmentNumber",
"targetDataType": "double"
}, {
"name": "departmentType",
"sourceDataType": "number",
"targetField": "departmentType",
"targetDataType": "double"
}, {
"name": "startDate",
"sourceDataType": "timestamp",
"targetField": "startDate",
"targetDataType": "date"
}],
"foriegnkey": [{
"parentTable": "Employee",
"parentkey": "employeeId",
"childTable": "department",
"childKey": "empId"
}]
}
}
}

}

我的代码:

public class DataParse {

public static void main(String a[]){

String FILEPATH = "C:\\Users\\BNSK\\Downloads\\simple.json";

Map<String,Object> resultMap = new HashMap<String,Object>();
ObjectMapper mapperObj = new ObjectMapper();

System.out.println("Input Json: "+FILEPATH);
try {
resultMap = mapperObj.readValue(new File(FILEPATH),
new TypeReference<HashMap<String,Object>>(){});
System.out.println("Output Map: "+resultMap);


for (String key : resultMap.keySet()) {
Object routings= resultMap.get(key);
System.out.println(routings);

}



} catch (IOException e) {

e.printStackTrace();
}
}

最佳答案

Elliot 是对的,我还想补充一点,在 Java 8 中,您可以使用流(和 lambda 表达式)轻松迭代 Map 键

resultMap.keySet().stream().forEach(key -> {
// do your thing here
});

关于java - 如何使用 for 循环使用键集迭代 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35679780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com