获取List中Map的属性值列表,获取所有map对象的某个属性列表

获取List<Map<String, Object>中Map的属性值列表,

获取所有map对象的某个属性列表

================================

©Copyright 蕃薯耀 2021-06-29

https://www.cnblogs.com/fanshuyao/

    /**
     * 获取List列表中的Map对象属性的值
     * @param <T>
     * @param list List<Map<String, Object>> 
     * @param mapValueName Map对象属性名
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> getMapValues(List<Map<String, Object>> list, String mapValueName) throws Exception{
        
        log.info("mapValueName = " + mapValueName);
        
        if(StringUtils.isBlank(mapValueName)) {
            throw new ValidationException("Map对象属性名不能为空");
        }
        
        List<T> objectidList = new ArrayList<T>();
        
        for (Map<String, Object> map : list) {
            objectidList.add((T) map.get(mapValueName));
        }
        return objectidList;
    }

Main方法

    public static void main(String[] args) throws Exception {

        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("name", "aa");
        map1.put("age", 25);
        map1.put("long", 10000000000L);
        map1.put("double", 10000.25d);
        
        
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("name", "bb");
        map2.put("age", 24);
        map2.put("long", 20000000000L);
        map2.put("double", 20000.25d);
        
        Map<String, Object> map3= new HashMap<String, Object>();
        map3.put("name", "cc");
        map3.put("age", 26);
        map3.put("long", 30000000000L);
        map3.put("double", 30000.25d);
        
        list.add(map1);
        list.add(map2);
        list.add(map3);
        
        List<String> listResult = getMapValues(list, "name");
        System.out.println(listResult);
        
        List<Integer> listAge = getMapValues(list, "age");
        System.out.println(listAge);
        
        List<Long> listLong = getMapValues(list, "long");
        System.out.println(listLong);
        
        List<Long> listDouble = getMapValues(list, "double");
        System.out.println(listDouble);
    }

输出结果:

mapValueName = name
[aa, bb, cc]

mapValueName = age
[25, 24, 26]

mapValueName = long
[10000000000, 20000000000, 30000000000]

mapValueName = double
[10000.25, 20000.25, 30000.25]

================================

©Copyright 蕃薯耀 2021-06-29

https://www.cnblogs.com/fanshuyao/