龙空技术网

Java从Map中获取多层级的key技巧

会点代码的80后 177

前言:

此时看官们对“获取map的key和value”大约比较注意,我们都需要剖析一些“获取map的key和value”的相关文章。那么小编也在网摘上网罗了一些对于“获取map的key和value””的相关资讯,希望兄弟们能喜欢,你们一起来学习一下吧!

实现方式一:

/** * 从map中获取多层级的key 如:parentKey.childKey... * @param map * @param key * @return 从map中获取的value<br   /> * Map {"parentKey":{"childKey":"value"}}<br/> * getValueFromMapWithMultiLevel(map, "parentKey.childKey") 返回 value */public static Object getValueFromMapMultiLevel(Map<String, Object> map, String key){  if (key.contains(".")) {    String[] keys = key.split("\\.");    for (int i = 0; i < keys.length - 1; i++) {      Object tmpMap = map.get(keys[i]);      if (tmpMap instanceof Map) {        map = (Map<String, Object>) tmpMap;      } else {        return null;      }    }    return map.get(keys[keys.length - 1]);  } else {    return map.get(key);  }}

实现方式一:

/** * 从map中获取多层级key的值 如: parentKey.childKey... */public static Object getValueFromMapMultiLevel2(Map<String,Object>  map, String key){  return getValueFromMultiLevel(map, key, Object.class);}/** * 从map中获取多层级key的值,返回值为clazz类型 */public static <T> T getValueFromMultiLevel(Map<String,Object>  map, String key, Class<T> clazz) {  if (map == null) {    return null;  }  StringTokenizer s = new StringTokenizer(key, ".");  T result;  try {    Object temp = map;    while (s.hasMoreElements()) {      String tempKey = (String) s.nextElement();      if (temp instanceof Map) {        temp = org.apache.commons.collections.MapUtils.MapUtils.getObject((Map) temp, tempKey);      } else {        Class tempClazz = temp.getClass();        Field field = tempClazz.getDeclaredField(tempKey);        field.setAccessible(true);        temp = field.get(temp);      }    }    result = com.alibaba.fastjson.util.TypeUtils.cast(temp, clazz, null);  } catch (Exception e) {    return null;  }  return result;}

测试效果

public static void main(String[] args) {  Map a = new HashMap();  Map b = new HashMap();  b.put("b","ab");  a.put("a",b);  System.out.println(getValueFromMapMultiLevel(a, "a.b"));  System.out.println(getValueFromMapMultiLevel2(a, "a.b"));}

标签: #获取map的key和value #如何获取map的key值