1.map 和 bean互转工具
package com.newnewbank.utils.bean; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import org.apache.log4j.Logger; public class BeanMapConvertUtil { private static Logger logger = Logger.getLogger(BeanMapConvertUtil.class); public static Map<String, Object> beanToMap(Object bean){ if(bean == null){ return null; } Map<String, Object> map = new HashMap<String, Object>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); // 过滤class属性 if (!key.equals("class")) { // 得到property对应的getter方法 Method getter = property.getReadMethod(); Object value = getter.invoke(bean); map.put(key, value); } } } catch (Exception e) { System.out.println("transBean2Map Error " + e); } return map; } public static <T> T mapToBean(Map<String, Object> map, T bean){ try { BeanUtils.populate(bean, map); } catch (IllegalAccessException | InvocationTargetException e) { logger.error(e, e.fillInStackTrace()); } return bean; } }2.HashMap的Key和Value排序
HashMap根据Key或者Value上升序列(从小到大)的两种排序方式:
Map map = new HashMap(); map.put("d", 2); map.put("c", 1); map.put("b", 1); map.put("a", 3); List> infoIds = new ArrayList>(map.entrySet()); //排序前 for (int i = 0; i < infoIds.size(); i++) { String id = infoIds.get(i).toString(); System.out.println(id); } //d 2 //c 1 //b 1 //a 3 //排序 Collections.sort(infoIds, new Comparator>() { public int compare(Map.Entry o1, Map.Entry o2) { //return (o2.getValue() - o1.getValue()); return (o1.getKey()).toString().compareTo(o2.getKey()); } }); //排序后 for (int i = 0; i < infoIds.size(); i++) { String id = infoIds.get(i).toString(); System.out.println(id); } //根据key排序 //a 3 //b 1 //c 1 //d 2 //根据value排序 //a 3 //d 2 //b 1 //c 13.Map<String, String> 遍历
(1)遍历key和value
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }(2)遍历所有的value
for (String v : map.values()) { System.out.println("value= " + v); }
