Java list转map,list转list

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011067966/article/details/80780741
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);

猜你喜欢

转载自blog.csdn.net/u011067966/article/details/80780741