`
zyslovely
  • 浏览: 228113 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

使用反射机制将 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);
		for (Profile profile : profileList) {
			pMap.put(profile.getUserId(), profile);
		}
		long time2 = new Date().getTime();
		System.out.println((time2 - time1));
	}

10W个数据,消耗时间为88ms

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,效率还是比较高的
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics