1. 程式人生 > >Java list轉map,list轉list

Java list轉map,list轉list

public class ListToListOrMapUtils {
    public static List list2list(List list, String fieldName4Key,Class<?> c) {
        /**
         *@param
         * list:輸入list
         * fieldName4Key:欄位名
         * c:類
         */
        List<Object> objectArrayList = new ArrayList<>();
        if
(list != null) { try { PropertyDescriptor propDesc = new PropertyDescriptor(fieldName4Key, c); Method methodGetKey = propDesc.getReadMethod(); for (int i = 0; i < list.size(); i++) { Object o = list.get(i); Object invoke = methodGetKey.invoke(o); if
(null != invoke){ objectArrayList.add(invoke); } } } catch (Exception e) { e.printStackTrace(); throw new IllegalArgumentException("field can't match the key!"); } } return
objectArrayList; } public static <K, V> Map<K, V> list2Map(List<V> list, String fieldName4Key,Class<V> c) { Map<K, V> map = new HashMap<K, V>(); if (list != null) { try { PropertyDescriptor propDesc = new PropertyDescriptor(fieldName4Key, c); Method methodGetKey = propDesc.getReadMethod(); for (int i = 0; i < list.size(); i++) { V value = list.get(i); @SuppressWarnings("unchecked") K key = (K) methodGetKey.invoke(value); map.put(key, value); } } catch (Exception e) { throw new IllegalArgumentException("field can't match the key!"); } } return map; }

用法如下:

Map<Object, User> userMap = ListToListOrMapUtils.list2Map(userList, "id", User.class);
List uidList = ListToListOrMapUtils.list2list(userList, "uid", User.class);