将list中对象的两个属性批量转换至map中(只支持字符串属性)

public class ListUtil {
	/**
     * 将list中对象的两个属性批量转换至map中(支持字符串属性)
     * @param list
     * @param listProp
     * @param <T>
     * @return
     */
    public static <T> Map<String, String> listPropToStrMap(List<T> list, String[] listProp) {
        Map<String, String> map = new HashMap<String, String>();
        String fieldOne = listProp[0]; // 属性名称1
        String fieldTwo = listProp[1]; // 属性名称2
        Class clazz = list.get(0).getClass();
        try {
            Field field1 = clazz.getDeclaredField(fieldOne);
            Field field2 = clazz.getDeclaredField(fieldTwo);
            field1.setAccessible(true);
            field2.setAccessible(true);
            for (T t : list) {
                map.put(field1.get(t) + "", field2.get(t) + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}

测试方法:

public class ListUtilTest {
	/**
     * 测试将list中对象的属性转换至字符串Map中
     */
    @Test
    public void testListPropToStrMap() {
        List<Student> studentList = new ArrayList<Student>();
        Student s = new Student();
        s.setSid("101");
        s.setSname("张三");
        studentList.add(s);

        s = new Student();
        s.setSid("102");
        s.setSname("李四");
        studentList.add(s);

        s = new Student();
        s.setSid("103");
        s.setSname("王五");
        studentList.add(s);

        Map<String, String> map1 = ListUtil.listPropToStrMap(studentList, new String[]{"sid", "sname"});
        Map<String, String> map2 = ListUtil.listPropToStrMap(studentList, new String[]{"sname", "sid"});
        System.out.println(map1);
        System.out.println(map2);
    }
}

Student.java

public class Student {

    private String sid; // 学生id
    private String sname; // 学生姓名
    private int sage; // 学生年龄

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public int getSage() {
        return sage;
    }

    public void setSage(int sage) {
        this.sage = sage;
    }
}


猜你喜欢

转载自blog.csdn.net/u010999809/article/details/80993876
0条评论
添加一条新回复