小创新,不同业务场景使用不同的map

   System.out.println("Map当Key一样,后面的value会覆盖前面的value");
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		map.put(1, 2);
		map.put(1, 3);
		System.out.println(map.get(1));    // 3
		System.out.println(map.keySet());   //[1]
		System.out.println(map.containsValue(2));   //false
		System.out.println(map.containsKey(1));   //true
		
		System.out.println("------------------------------");
		
		System.out.println("MultiValueMap 当Key一样,value不一样,不会覆盖");
		MultiValueMap map2 = new MultiValueMap();
		map2.put(1, 2);
		map2.put(1, 3);
		System.out.println(map2.get(1));    // [2,3]
		System.out.println(map2.keySet());  //[1]
		System.out.println(map2.containsValue(2));  //true
		System.out.println(map2.containsKey(1));  //true


该程序是一个单线程时间调度程序。
用途:每台机器需要定时执行的程序。比如: 更新本地缓存,更新索引文件,定时数据分析计算,定时发邮件,旺旺等等。
说明:1,需要考虑定时执行的任务在设定时间内是否能顺利完成,否则容易积压任务。
2,需要考虑本地缓存的数据结构的读写同步

private static Map configMap = new ConcurrentHashMap(20);
	private ScheduledExecutorService scheduledExecutorService;

	public void init() {
		reloadCache();
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 每隔10分钟自动更新一次
		scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				reloadCache();
			}
		}, 1, 10, TimeUnit.MINUTES);
	}

	private void reloadCache() {
		// 需要定时调度的任务,比如: 可以更新本类的静态MAP 等等。
	}



将一个普通java对象转换成Map. 一般我们会通过Class对象的getFields()来获取所有属性,然后通过遍历所有属性生成Getter的方法名,通过调用getDeclaredMethod()来获取getter方法,然后invork()得到属性值.


反射的效率很高,但是上述获取getter方法的代价还是比较大.高效的话需要自己对Class的getter方法做cache.
用BeanInfo的方式获取的话,jdk内部实现自动对做过调用的class做了缓存,所以效率更好.
public static Map<String, Object> convertBean(Object bean,
	Set<String> excludeProperties) throws IntrospectionException,
	IllegalArgumentException, IllegalAccessException,
	InvocationTargetException {
		Class<?> type = bean.getClass();
		Map<String, Object> objMap = new HashMap<String, Object>();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
			String propertyName = propertyDescriptor.getName();
			if (!"class".equals(propertyName)) {

				Method readMethod = propertyDescriptor.getReadMethod();

				Object result = readMethod.invoke(bean, new Object[0]);

				objMap.put(propertyName, result != null
						&& result.getClass().isEnum() ? result.toString()
						: result);
			}
		}
		return objMap;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值