九、工具类方法-判空、dto与map互转(借助工具类/自我实现)、日期格式化、枚举、dto的list去重(性能比较)、dto复制(3种方法)
1.commons-lang.jar包下面 生成随机数
//生成一个十位的随机标识org.apache.commons.lang3.RandomStringUtils#randomNumeric //String random = RandomStringUtils.randomNumeric(10); <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency>
2.日期格式化:
public static String formatDate(Date dateTime, String pattern) { if (dateTime != null && !StringUtils.isEmpty(pattern)) { DateFormat df = new SimpleDateFormat(pattern); String result = df.format(dateTime); return result; } else { return ""; } } 备注:pattern可能的取值 public static final String FORMAT_LONG0 = "yyyyMMddHHmmss"; public static final String FORMAT_LONG = "yyyy-MM-dd HH:mm:ss"; public static final String FORMAT_LONG2 = "yyyy/MM/dd HH:mm:ss"; public static final String FORMAT_LONG3 = "yyyy.MM.dd HH:mm:ss"; public static final String FORMAT_LONG4 = "yyyy-MM-dd"; public static final String FORMAT_LONG5 = "yyyyMMddHHmmssSSS";
3.判断是否为空:
//3.1字符串判断是否为空 public static boolean isEmpty(String str) { return str == null || str.length() == 0; } //3.2集合判断是否为空: commons-collections.jar下面 org.apache.commons.collections.CollectionUtils#isEmpty public static boolean isEmpty(Collection coll) { return coll == null || coll.isEmpty(); } //3.4集合map是否为空: commons-collections.jar下面 public static boolean isEmpty(Map map) { return map == null || map.isEmpty(); } //3.4检验一个对象的所有入参字段是否为空 全不为空-ture private boolean checkAllFieldIsNull(Object obj) { Class itemReturnClass = obj.getClass(); Field[] fields = itemReturnClass.getDeclaredFields(); boolean flag = true; try { for (Field f : fields) { f.setAccessible(true); Object val = f.get(obj); if (val == null) { flag = false; break; } } } catch (Exception e) { //进行日志记录... flag = false; } return flag; }
4.字符串转数组、字符串转集合、dto与map之间的相互转化(借助工具类/自我实现)
1 //4.1 字符串转化为数组: alreadyUsers 为字符串 2 String[] paramString=alreadyUsers.split(","); 3 4 //4.2 字符串转为List集合: 5 //方法1:通过 Arrays.asList实现 6 List<String> alreadyUserList= Arrays.asList(alreadyUsers.split(",")); 7 8 //方法1:通过 fastJson的JSONArray类实现 9 String jsonUsers="[{\"userCode\":\"70001\"},{\"userCode\":\"70004\"}]"; 10 if(StringUtils.isNotEmpty(jsonUsers)){ 11 List<String> userCodeInfoList = JSONArray.parseArray(jsonUsers,String.class); 12 List<String> userCodes=new ArrayList<>(); 13 for(String ele:userCodeInfoList){ 14 if(StringUtils.isNotEmpty(ele)){ 15 JSONObject jsonObject = JSON.parseObject(ele); 16 String userCode= (String) jsonObject.get("userCode"); 17 if(StringUtils.isNotEmpty(userCode)){ 18 userCodes.add(userCode); 19 } 20 } 21 } 22 } 23 24 //4.3 dto和Map之间的相互转化: 25 方法1:通过commons-beanutils.jar包中的 org.apache.commons.beanutils.PropertyUtilsBean工具类 示列代码如下: 26 import org.apache.commons.beanutils.BeanUtils; 27 import org.apache.commons.beanutils.PropertyUtilsBean; 28 import java.beans.PropertyDescriptor; 29 import java.lang.reflect.InvocationTargetException; 30 import java.util.ArrayList; 31 import java.util.HashMap; 32 import java.util.List; 33 import java.util.Map; 34 35 public class BeanToMapUtil2 { 36 public static void main(String[] args) { 37 //通过 commons-beanutils.jar包中的工具类实现将dto对象转化为Map 38 Student student = new Student("2", "er"); 39 System.out.println("convertBeanToMap>>>"+convertBeanToMap(student)); 40 41 42 43 Map<String,Object> param=new HashMap<>(); 44 param.put("id","55"); 45 param.put("name","测试"); 46 System.out.println("convertMapToBean>>>"+convertMapToBean(param)); 47 48 } 49 50 /* 51 *@Description:将bean转化为map 52 *@Date 2020/5/7 15:59 53 *@Param 54 *@return 55 **/ 56 public static Map<String, Object> convertBeanToMap(Object obj) { 57 HashMap params = new HashMap(0); 58 try { 59 PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); 60 PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj); 61 for (int i = 0; i < descriptors.length; ++i) { 62 String name = descriptors[i].getName(); 63 if (!"class".equals(name)) { 64 params.put(name, propertyUtilsBean.getNestedProperty(obj, name)); 65 } 66 } 67 } catch (Exception var6) { 68 System.out.println(var6); 69 } 70 return params; 71 } 72 73 /* 74 *@Description:将map转化为bean 75 *@Date 2020/5/7 15:59 76 *@Param 77 *@return 78 **/ 79 public static List<Student> convertMapToBean(Map<String,Object> studentMap){ 80 List<Student> resultStudent=new ArrayList<>(); 81 if (studentMap.size()>0) { 82 Student student =new Student(); 83 for(Map.Entry<String,Object> entry : studentMap.entrySet()) { 84 copyPropertyToBean(student,entry.getKey(),entry.getValue()); 85 } 86 resultStudent.add(student); 87 } 88 return resultStudent; 89 } 90 91 public static void copyPropertyToBean(Object obj,String name,Object value) { 92 try { 93 BeanUtils.copyProperty(obj,name,value); 94 } catch(IllegalAccessException| InvocationTargetException e) { 95 e.printStackTrace(); 96 } 97 } 98 99 } 100 101 //方法2:自己实现 示列代码如下: 102 import com.alibaba.fastjson.JSON; 103 import org.apache.commons.lang3.StringUtils; 104 105 import java.beans.BeanInfo; 106 import java.beans.IntrospectionException; 107 import java.beans.Introspector; 108 import java.beans.PropertyDescriptor; 109 import java.lang.reflect.InvocationTargetException; 110 import java.lang.reflect.Method; 111 import java.util.HashMap; 112 import java.util.Map; 113 114 public class BeanToMapUtil1 { 115 116 public static void main(String[] args) { 117 118 119 UserDto userDto = new UserDto(); 120 userDto.setCode("01"); 121 userDto.setUserName("李四"); 122 userDto.setAddress("北京市海淀区"); 123 //自己实现将bean转化为Map 124 Map<String, Object> stringObjectMap1 = convertBeanToMap(userDto); 125 System.out.println("beanToMap>>>"+ JSON.toJSON(stringObjectMap1)); 126 127 128 //自己实现将map转化为Bean对象 129 Map<String, Object> stringObjectMap = new HashMap<>(); 130 stringObjectMap.put("address", "北京市朝阳区"); 131 stringObjectMap.put("userName", "张三"); 132 stringObjectMap.put("code", "11"); 133 try { 134 //map 转化为javaBean 135 Object resultObject=convertMapToBean(userDto.getClass(), stringObjectMap); 136 System.out.println("convertMapToBean>>>"+ JSON.toJSON(resultObject)); 137 } catch (IntrospectionException e) { 138 e.printStackTrace(); 139 } catch (IllegalAccessException e) { 140 e.printStackTrace(); 141 } catch (InstantiationException e) { 142 e.printStackTrace(); 143 } catch (InvocationTargetException e) { 144 e.printStackTrace(); 145 } 146 } 147 148 /** 149 * 将一个 JavaBean 对象转化为一个 Map 150 * @param bean 要转化的JavaBean 对象 151 * @return 转化出来的 Map 对象 152 * @throws IntrospectionException 如果分析类属性失败 153 * @throws IllegalAccessException 如果实例化 JavaBean 失败 154 * @throws InvocationTargetException 如果调用属性的 setter 方法失败 155 */ 156 @SuppressWarnings("rawtypes") 157 public static Map<String, Object> convertBeanToMap(Object bean) { 158 Class<? extends Object> clazz = bean.getClass(); 159 Map<String, Object> returnMap = new HashMap<String, Object>(); 160 BeanInfo beanInfo = null; 161 try { 162 beanInfo = Introspector.getBeanInfo(clazz); 163 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); 164 for (int i = 0; i < propertyDescriptors.length; i++) { 165 PropertyDescriptor descriptor = propertyDescriptors[i]; 166 String propertyName = descriptor.getName(); 167 if (StringUtils.isNotEmpty(propertyName) && !"class".equals(propertyName)) { 168 Method readMethod = descriptor.getReadMethod(); 169 Object result = null; 170 result = readMethod.invoke(bean, new Object[0]); 171 propertyName = propertyName.toString(); 172 if (null != result) { 173 result = result.toString(); 174 } 175 returnMap.put(propertyName, result); 176 } 177 } 178 } catch (Exception e) { 179 //异常日志信息捕获并打印 180 181 } 182 return returnMap; 183 } 184 185 /** 186 * 将一个 Map 对象转化为一个 JavaBean 187 * @param type 要转化的类型 188 * @param map 包含属性值的 map 189 * @return 转化出来的 JavaBean 对象 190 * @throws IntrospectionException 如果分析类属性失败 191 * @throws IllegalAccessException 如果实例化 JavaBean 失败 192 * @throws InstantiationException 如果实例化 JavaBean 失败 193 * @throws InvocationTargetException 如果调用属性的 setter 方法失败 194 */ 195 public static Object convertMapToBean(Class type, Map map) 196 throws IntrospectionException, IllegalAccessException, 197 InstantiationException, InvocationTargetException { 198 BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性 199 Object obj = type.newInstance(); // 创建 JavaBean 对象 200 try { 201 // 给 JavaBean 对象的属性赋值 202 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); 203 for (int i = 0; i < propertyDescriptors.length; i++) { 204 PropertyDescriptor descriptor = propertyDescriptors[i]; 205 String propertyName = descriptor.getName(); 206 if (map.containsKey(propertyName)) { 207 // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。 208 Object value = map.get(propertyName); 209 210 Object[] args = new Object[1]; 211 args[0] = value; 212 descriptor.getWriteMethod().invoke(obj, args); 213 } 214 } 215 } catch (Exception e) { 216 //异常日志信息捕获并打印 217 } 218 return obj; 219 } 220 221 }
5.开发中枚举的使用
1 public enum OrderStatusEnum { 2 ALL("0", "全部"), 3 TO_REVIEW("1", "待审核"), 4 REVIEW_PASS("3", "审核通过"), 5 REVIEW_NOPASS("4", "审核不通过"); 6 private String code; 7 private String desc; 8 9 private OrderStatusEnum(String code, String desc) { 10 this.code = code; 11 this.desc = desc; 12 } 13 14 public String getCode() { 15 return code; 16 } 17 public String getDesc() { 18 return desc; 19 } 20 //判断枚举的所有key是否包含某个值 21 public static boolean isStatusExist(String status) { 22 for (OrderStatusEnum temp : OrderStatusEnum.values()) { 23 if (temp.getCode().equals(status)) { 24 return true; 25 } 26 } 27 return false; 28 } 29 }
7.对List去重的所有方法(性能排序)
1 public class DtoListRemoveDuplicate { 2 3 public static void main(String[] args) { 4 //将List去重的所有方法:耗时大小依次为:3<4<1<2 5 6 List<Student> stuList1 = makeList(); 7 //1.通过Array的集合构造器进行:如果是去重的是对象需要重新hashcode 和 equals方法 8 listRemoveDuplicateByArrayListCollectionConstructs(stuList1); 9 10 //2.通过List的remove方法:在数据量较小的时候很快,但是当数据量大的时候会N的平方次循环耗时很长,不建议采用此种方式 11 List<Student> stuList2 = makeList(); 12 listRemoveDuplicateByListRemoveMethod(stuList2); 13 14 //3.把list里的对象遍历一遍,用list.contain(),如果不存在就放入到另外一个list集合中 15 List<Student> stuList3 = makeList(); 16 listRemoveDuplicateByListContainsMethod(stuList3); 17 18 //4.删除ArrayList中重复元素,保持顺序 19 List<Student> stuList4 = makeList(); 20 listRemoveDuplicateByListClearMethod(stuList4); 21 22 } 23 24 public static List makeList() { 25 List<Student> stuList = new ArrayList<Student>(); 26 for (int i = 0; i < 1000000; i++) { 27 stuList.add(new Student("2", "er")); 28 stuList.add(new Student("3", "san")); 29 } 30 return stuList; 31 } 32 33 //1.通过Array的集合构造器进行:如果是去重的是对象需要重新hashcode 和 equals方法,建议采用此种方式 34 public static void listRemoveDuplicateByArrayListCollectionConstructs(List<Student> stuList) { 35 long start = System.currentTimeMillis(); 36 //set集合保存的是引用不同地址的对象 37 Set<Student> studentSet = new HashSet<Student>(); 38 studentSet.addAll(stuList); 39 List<Student> finalstuList = new ArrayList<Student>(studentSet); 40 System.out.println("listRemoveDuplicateByArrayListCollectionConstructs去重之后的List>>>finalstuList=" + JSON.toJSONString(finalstuList)); 41 long end = System.currentTimeMillis(); 42 System.out.println("listRemoveDuplicateByArrayListCollectionConstructs去重耗时>>>" + JSON.toJSONString((end - start) / 1000) + "秒" + (end - start) % 1000 + "毫秒"); 43 } 44 45 //2.通过List的remove方法:在数据量较小的时候很快,但是当数据量大的时候会N的平方次循环耗时很长,不建议采用此种方式 46 public static void listRemoveDuplicateByListRemoveMethod(List list) { 47 long start = System.currentTimeMillis(); 48 if (CollectionUtils.isNotEmpty(list)) { 49 for (int i = 0; i < list.size() - 1; i++) { 50 for (int j = list.size() - 1; j > i; j--) { 51 if (list.get(j).equals(list.get(i))) { 52 list.remove(j); 53 } 54 } 55 } 56 } 57 long end = System.currentTimeMillis(); 58 System.out.println("listRemoveDuplicateByListRemoveMethod去重之后的List>>>" + JSON.toJSONString(list)); 59 System.out.println("listRemoveDuplicateByListRemoveMethod去重耗时>>>" + JSON.toJSONString((end - start) / 1000) + "秒" + (end - start) % 1000 + "毫秒"); 60 } 61 62 //3.把list里的对象遍历一遍,用list.contain(),如果不存在就放入到另外一个list集合中 63 public static void listRemoveDuplicateByListContainsMethod(List list){ 64 long start = System.currentTimeMillis(); 65 List listTemp = new ArrayList(); 66 for(int i=0;i<list.size();i++){ 67 if(!listTemp.contains(list.get(i))){ 68 listTemp.add(list.get(i)); 69 } 70 } 71 long end = System.currentTimeMillis(); 72 System.out.println("listRemoveDuplicateByListContainsMethod去重之后的List>>>" + JSON.toJSONString(listTemp)); 73 System.out.println("listRemoveDuplicateByListContainsMethod去重耗时>>>" + JSON.toJSONString((end - start) / 1000) + "秒" + (end - start) % 1000 + "毫秒"); 74 } 75 76 //4.遍历集合并将每个元素放入set中,如果往set中添加成功,则表示该元素非重复元素,否则为重复元素 77 public static void listRemoveDuplicateByListClearMethod(List list){ 78 long start = System.currentTimeMillis(); 79 Set set = new HashSet(); 80 List newList = new ArrayList(); 81 for (Iterator iter = list.iterator(); iter.hasNext();) { 82 Object element = iter.next(); 83 if (set.add(element)){ 84 newList.add(element); 85 } 86 } 87 list.clear(); 88 list.addAll(newList); 89 long end = System.currentTimeMillis(); 90 System.out.println("listRemoveDuplicateByListClearMethod去重之后的List>>>" + JSON.toJSONString(list)); 91 System.out.println("listRemoveDuplicateByListClearMethod去重耗时>>>" + JSON.toJSONString((end - start) / 1000) + "秒" + (end - start) % 1000 + "毫秒"); 92 } 93 } 94 95 public class Student { 96 public String id; 97 public String name; 98 public Student() { 99 } 100 public Student(String id,String name) { 101 this.id = id; 102 this.name = name; 103 } 104 public String getId() { 105 return id; 106 } 107 public void setId(String id) { 108 this.id = id; 109 } 110 public String getName() { 111 return name; 112 } 113 public void setName(String name) { 114 this.name = name; 115 } 116 @Override 117 public boolean equals(Object obj) { 118 Student s=(Student)obj; 119 return id.equals(s.id) && name.equals(s.name); 120 } 121 @Override 122 public int hashCode() { 123 String in = id + name; 124 return in.hashCode(); 125 } 126 127 @Override 128 public String toString() { 129 return "Student{" + 130 "id='" + id + '\'' + 131 ", name='" + name + '\'' + 132 '}'; 133 } 134 }
8.对String 类型的List去重的方法
public class StringListRemoveDuplicate { public static void main(String[] args) { //对String 类型的List去重: //1.通过 List<String> finalStringList = new ArrayList<String>(stringSet); 实现对String类型的List去重的原理 stringListRemoveDuplicatMeth1(); //2.通过将set 的addAll 方法实现list集合去重 stringListRemoveDuplicatMeth2(); } public static void stringListRemoveDuplicatMeth1(){ List<String> stringList= Arrays.asList("123","456","123"); System.out.println("未去重之前的List>>>stringList="+ JSON.toJSONString(stringList)); //排重set Set<String> stringSet = new HashSet<>(); if(CollectionUtils.isNotEmpty(stringList)){ for(String ele:stringList){ stringSet.add(ele); } } List<String> finalStringList = new ArrayList<String>(stringSet); System.out.println("去重之后的List>>>finalStringList="+ JSON.toJSONString(finalStringList)); } public static void stringListRemoveDuplicatMeth2(){ List<String> stringList= Arrays.asList("123","456","123"); System.out.println("stringListRemoveDuplicatMeth2未去重之前的List>>>stringList="+ JSON.toJSONString(stringList)); //排重set Set<String> stringSet = new HashSet<>(); stringSet.addAll(stringList); List<String> finalStringList = new ArrayList<String>(stringSet); System.out.println("stringListRemoveDuplicatMeth2去重之后的List>>>finalStringList="+ JSON.toJSONString(finalStringList)); } }
9.对dto进行复制的三种方法
1 方法1:通过apache的beanutils工具实现:只要属性相同,类名可以相同也可以不相同,并且支持属性为List的赋值 2 需要引入:下面的2个jar包,commons-beanutils是依赖logging包的 3 <dependency> 4 <groupId>commons-beanutils</groupId> 5 <artifactId>commons-beanutils</artifactId> 6 <version>1.9.2</version> 7 </dependency> 8 9 <dependency> 10 <groupId>commons-logging</groupId> 11 <artifactId>commons-logging</artifactId> 12 <version>1.9.2</version> 13 </dependency> 14 org.apache.commons.beanutils.BeanUtils#copyProperties(Object dest, Object orig) 15 16 方法2:通过fastjson实现 17 <dependency> 18 <groupId>com.alibaba</groupId> 19 <artifactId>fastjson</artifactId> 20 <version>${fastJson.version}</version> 21 </dependency> 22 备注:不同类型的对象也是可以实现复制的,只要属性名称相同即可 23 String jsonString = JSON.toJSONString(yuanMiao); 24 fuzhiMiao = JSON.parseObject(jsonString, AnimalDTO.class); 25 26 方法2:通过 spring-beans-3.1.2.RELEASE.jar 工具包中的copyProperties方法进行复制 27 org.springframework.beans.BeanUtils#copyProperties(java.lang.Object, java.lang.Object) 28 备注:该工具方法有坑,如果属性中还有List属性,那么该List属性是无法实现复制的...,这是spring自身的坑.
整理上述工具类中的完全是为了巩固一下基础、提高开发效率,基础好的伙伴 参考价值不大!
细水长流,打磨濡染,渐趋极致,才是一个人最好的状态。

浙公网安备 33010602011771号