Java泛型將List轉換成Map

/**
* @功能描述: 通過字段名稱將list轉換成Map
* 以對應的字段的值作爲key,對應的對象作爲value
* @param list
* @param fieldName4Key
* @param c
* @return 
* @date 2017年3月31日
* @author WEISANGENG
*/
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> listToMapByFiledName(List<V> list, String keyFieldName,Class<V> c) {  
        Map<K, V> map = new HashMap<K, V>();  
        if (list != null) {  
            try {
            //根據字段屬性名稱獲取對應的字段信息
                PropertyDescriptor propDesc = new PropertyDescriptor(keyFieldName, c);
                //獲取字段讀的方法,即get方法
                Method methodGetKey = propDesc.getReadMethod();  
                for (int i = 0; i < list.size(); i++) {  
                    V value = list.get(i);  
                    K key = (K) methodGetKey.invoke(list.get(i));  
                    map.put(key, value);  
                }  
            } catch (Exception e) {  
                throw new IllegalArgumentException("field can't match the key!");  
            }  
        }  
        return map;  
    }

/**
* @功能描述: 通過方法名稱將list轉換成map
* 以方法對應的屬性名稱爲key,屬性對應的對象爲value
* @param list
* @param keyMethodName
* @param c
* @return 
* @date 2017年3月31日
* @author WEISANGENG
*/
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> listToMapByMethodName(List<V> list, String keyMethodName,Class<V> c) {  
        Map<K, V> map = new HashMap<K, V>();  
        if (list != null) {  
            try {
            //根據方法名稱獲取對象方法
                Method methodGetKey = c.getMethod(keyMethodName);  
                for (int i = 0; i < list.size(); i++) {  
                    V value = list.get(i);  
                    //根據對象反射原理獲取屬性名稱
                    K key = (K) methodGetKey.invoke(list.get(i));  
                    map.put(key, value);  
                }  
            } catch (Exception e) {  
                throw new IllegalArgumentException("field can't match the key!");  
            }  
        }  
  
        return map;  
    }
發佈了45 篇原創文章 · 獲贊 29 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章