工作中遇到的一些问题总结(一)

1.根据出生年月算出年龄

一般公司都会封装出一个Utils的工具类,以下是我的写法(注意需要分别比较年,月,日):

 1   public Integer getAgeByBirthday(String birthday, Date currentTime) {
 2     Integer age = 0;
 3     String currentTimeStr = DateUtil.format(currentTime); // 转化为yyyyMMdd格式
 4     if (StringUtils.isNotBlank(birthday) && birthday.length() == 8) {
 5       String year = birthday.substring(0, 4);
 6       String monthAndDay = birthday.substring(4);
 7 
 8       String currentYear = currentTimeStr.substring(0, 4);
 9       String currentMonthAndDay = currentTimeStr.substring(4);
10       if (currentYear.compareTo(year) > 0) {
11         age = Integer.valueOf(currentYear) - Integer.valueOf(year) - 1;
12         if (currentMonthAndDay.compareTo(monthAndDay) >= 0) {
13           age++;
14         }
15       }
16     }
17     return Integer.toString(age);
18   }

2.Map按照key大小排序

可以借助Comparator来实现:

  private Map<Long, Long> sortMap(Map<Long, Long> map) {
    List<Map.Entry<Long, Long>> list =
        new ArrayList<Map.Entry<Long, Long>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<Long, Long>>() {
      public int compare(Map.Entry<Long, Long> o1, Map.Entry<Long, Long> o2) {
        Long compare = o2.getKey() - o1.getKey();
        return compare.intValue();
      }
    });
    Map<Long, Long> result = new LinkedHashMap<>();
    for (Map.Entry<Long, Long> entry : list) {
      result.put(entry.getKey(), entry.getValue());
    }
    return result;
  }

3.将对象Object转换为Map

利用反射,转换规则为:Map中的key是原对象的属性名,value是原来对象的属性值(不适合对象里面的属性也是对象)

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
 
public class MapUtil {
    /**
     *
     * @Title: objectToMap
     * @Description: 将object转换为map,默认不保留空值
     * @param @param obj
     * @return Map<String,Object> 返回类型
     * @throws
     */
    public static Map objectToMap(Object obj) {
 
        Map<String, Object> map = new HashMap<String, Object>();
        map = objectToMap(obj, false);
        return map;
    }
 
    public static Map objectToMap(Object obj, boolean keepNullVal) {
        if (obj == null) {
            return null;
        }
 
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Field[] declaredFields = obj.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                if (keepNullVal == true) {
                    map.put(field.getName(), field.get(obj));
                } else {
                    if (field.get(obj) != null && !"".equals(field.get(obj).toString())) {
                        map.put(field.getName(), field.get(obj));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}

 

posted @ 2019-03-26 15:04  black_air  阅读(276)  评论(0编辑  收藏  举报