码迷,mamicode.com
首页 > 其他好文 > 详细

list转map

时间:2019-02-09 17:44:29      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:sse   throw   integer   etc   tst   stat   als   ||   getc   

参考https://cloud.tencent.com/developer/article/1033706

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListToMap {
    //list转化为map
    public static <K, V> Map<K, V> listToMap(List<V> vList, String kName) {
        Map<K, V> map = new HashMap<K, V>();
        if (vList == null || kName == null || vList.size() == 0) {
            return map;
        }
        Field kField = getField(vList.get(0).getClass(), kName);
        for (V v : vList) {
            try {
                map.put((K) kField.get(v), v);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
    //获取key对应的类型字段
    private static <V> Field getField(Class<V> clazz, String kName) {
        if (clazz == null || kName == null) {
            return null;
        }
        for (Field fieldElem : clazz.getDeclaredFields()) {
            fieldElem.setAccessible(true);
            if (fieldElem.getName().equals(kName)) {
                return fieldElem;
            }
        }
        return null;
    }
    //调用示例
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        List<Person> pList = new ArrayList<Person>();
        Person p1 = new Person(2, "taxuexing");
        pList.add(p1);
        Person p2 = new Person(3, "jikewang");
        pList.add(p2);
        Map<Integer, Person> map = ListToMap.listToMap(pList, "age");

        System.out.println(map.get(2).getUserName());
        System.out.println(map.get(3).getUserName());
    }
}

  

public class Person {
    private String userName;
    private int age;
    Person(){

    }
    Person(int age, String userName){
        this.age = age;
        this.userName = userName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

  

list转map

标签:sse   throw   integer   etc   tst   stat   als   ||   getc   

原文地址:https://www.cnblogs.com/alice-cj/p/10357685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!