1. 程式人生 > 其它 >獲取List<Map<String, Object>中Map的屬性值列表,獲取所有map物件的某個屬性列表

獲取List<Map<String, Object>中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/