Map工具方法,类型匹配时返回对应的对象/List对象

223 阅读1分钟

Map工具方法,类型匹配时返回对应的对象/List对象

/**
* 根据key值从Map中获取对象值,当对象值与目标类型相匹配时才返回值,否则返回空
* 
* @param map 入参map
* @param key key
* @param clazz 目标类型
* @return 目标值
* @param <T> 目标对象类型
*/
public static <T> T getIfTypeMatch(Map<?, ?> map, String key, Class<T> clazz) {
    if (map == null) {
        throw new IllegalArgumentException("Map must not be null.");
    }
    Object value = map.get(key);
    if (clazz.isInstance(map.get(key))) {
        return clazz.cast(value);
    }
    return null;
}

/**
* 根据key从Map中获取目标List对象值,List里所有对象与入参类型一致时才返回值,否则返回空列表
* 
* @param map 入参map
* @param key key
* @param clazz 目标类型
* @return 目标列表
* @param <T> 目标对象类型
*/
public static <T> List<T> getListIfTypeMatch(Map<?, ?> map, String key, Class<T> clazz) {
    if (map == null) {
        throw new IllegalArgumentException("Map must not be null.");
    }
    Object value = map.get(key);
    if (value == null) {
        return Collections.emptyList();
    }
    if (!(value instanceof List)) {
        throw new IllegalArgumentException("getList fail: The value type in the map is not list.");
    }
    List<T> result = new ArrayList<>();
    for (Object obj : (List<?>) value) {
        if (clazz.isInstance(obj)) {
            result.add(clazz.cast(obj));
        } else {
            throw new IllegalArgumentException("getList fail: the types of objects in the list do not match.");
        }
    }
    return result;
}