不同业务场景使用不同的map

来源:互联网 发布:ubuntu在线音乐软件 编辑:程序博客网 时间:2024/05/18 02:50


   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
原创粉丝点击