使用path 格式获取java hashmap key 值

一个简单场景,需要通过字符串格式获取hashmap 的数据
参考请求格式

 
getvalue(hashmap,"<key>.<subkey>.<subkey>")

好处,我们不需要进行太多复杂的处理,就可以方便的获取支持嵌套hashmap的数据

参考工具类

package com.dalong;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MapPathUtils {
    // 处理包含数字
    private final static Pattern PATTERN_INDEX = Pattern
            .compile("^\\\\[(\\d+)\\]$");
    /**
     * Extracts a value from a target object using DPath expression.
     *
     * @param target
     * @param dPath
     */
    public static Object getValue(Object target, String dPath) {
        String[] paths = dPath.split("\\.");
        // 此处实现了一个可以支持递归模式的数据处理
        Object result = target;
        for (String path : paths) {
            result = extractValue(result, path);
        }
        return result;
    }
    private static Object extractValue(Object target, String index) {
        if (target == null) {
            throw new IllegalArgumentException();
        }
        Matcher m = PATTERN_INDEX.matcher(index);
        if (m.matches()) {
            int i = Integer.parseInt(m.group(1));
            if (target instanceof Object[]) {
                return ((Object[]) target)[i];
            }
            if (target instanceof List<?>) {
                return ((List<?>) target).get(i);
            }
            throw new IllegalArgumentException("Expect an array or list!");
        }
        if (target instanceof Map<?, ?>) {
            return ((Map<?, ?>) target).get(index);
        }
        throw new IllegalArgumentException();
    }
}

参考使用

  • 代码
package com.dalong;
import java.util.HashMap;
import java.util.Map;
public class Application {
    public static void main(String[] args) {
        Map  userinfo = new HashMap();
        Map  userinfo2 = new HashMap();
        userinfo2.put("name","rong");
        userinfo2.put("type","local");
        userinfo.put("name","dalongdemo");
        userinfo.put("age",333);
        userinfo.put("title",userinfo2);
        Object name = MapPathUtils.getValue(userinfo,"title.name");
        System.out.println(name);
    }
}
  • 运行效果

 

 

说明

基于path格式获取hashmap 的数据,可以简化我们的代码,比较适合我们需要灵活配置的系统,以上代码可以扩展,类似的对象
查询规范有jsonpath,xmlpath 。。。

posted on 2020-10-28 18:55  荣锋亮  阅读(513)  评论(0编辑  收藏  举报

导航