使用反射机制将 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,效率还是比较高的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值