我有一个hashmap,它具有String和object的键值对.这是json以下的转换.
{
"test1": {
"test2": {
"test3": {
"key": "value"
},
"somefields12": "some value2"
},
"somefields": "some value"
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我没有转换为地图.我只有那张地图.如果这可能有关键和值,我必须根据该值编写一些逻辑.我实现如下:
if (map.containsKey("test1") ) {
final HashMap<String, Object> test1 = (HashMap<String, Object>) map.get("test1");
if (test1.containsKey("test2")) {
final List<Object> test2 = (List<Object>) test1.get("test2");
if (!test2.isEmpty()) {
final HashMap<String, Object> test3 = (HashMap<String, Object>) test2.get(0);
if (test3.containsKey("key")) {
final String value = String.valueOf(test2.get("key"));
if (!StringUtils.isBlank(value)) {
//do some work based on value
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我想避免从我的代码中嵌套if(多个ifs).最好的方法是什么?
我不熟悉新奇的 Java 8 功能,因此我会使用老式的方法,使用一个函数来查找路径,并使用循环遍历列表:
import java.util.*;
class Test {
static String getByPath(HashMap<String, Object> map, String... path) {
for(int i=0; i<path.length-1; i++) {
map = (HashMap<String, Object>) map.get(path[i]);
if (map == null) return null;
}
Object value = map.get(path[path.length-1]);
return value == null ? null : String.valueOf(value);
}
public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>();
HashMap<String, Object> tmp1 = new HashMap<>();
HashMap<String, Object> tmp2 = new HashMap<>();
map.put("test1", tmp1);
tmp1.put("test2", tmp2);
tmp2.put("key1", "My Value");
System.out.println("With valid path: " + getByPath(map, "test1", "test2", "key1"));
System.out.println("With invalid path: " + getByPath(map, "test1", "BANANA", "key1"));
}
}
Run Code Online (Sandbox Code Playgroud)
这导致:
With valid path: My Value
With invalid path: null
Run Code Online (Sandbox Code Playgroud)
这可以选择性地扩展到:
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |