首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

使用反射机制将 list转为地图

2012-09-13 
使用反射机制将 list转为mappublic static void main(String[] args) {ListProfile profileList new A

使用反射机制将 list转为map

public static void main(String[] args) {List<Profile> profileList = new ArrayList<Profile>(100000);for (int i = 0; i < 100000; i++) {Profile profile = new Profile();profile.setUserId(i);profile.setUserName("zystest1");profileList.add(profile);}long time1 = new Date().getTime();Map<Long, Profile> pMap = new HashMap<Long, Profile>(100000);try {pMap = Test.ListToMap(profileList, "getUserId", Profile.class,100000);} catch (Exception e) {e.printStackTrace();}long time2 = new Date().getTime();System.out.println((time2 - time1));}public static <T> Map<Long, T> ListToMap(List<T> objects,String methodName, Class class1, int initSize) {Map<Long, T> pMap = new HashMap<Long, T>(initSize);try {Method method = class1.getMethod(methodName);for (T t : objects) {Long long1 = (Long) method.invoke(t);pMap.put(long1, t);}} catch (Exception e) {e.printStackTrace();}return pMap;}

使用反射机制做listToMap,耗时98ms

总体来说,只要不循环定义method,效率还是比较高的

热点排行