java一些比较实用的方法,持续更新中

1、将json格式的字符串转换成List

 List<PointBean> list = new GsonBuilder().create().fromJson(resultStr, new TypeToken<List<PointBean>>() {

        }.getType());

StringEscapeUtils.unescapeJavaScript(str1);---------------去除json字符串的反斜杠

2、Stream API的一些用法

将以逗号分隔的一些id转成list时,如果要对list进行操作时,必须转换成ArrayList后才能操作,否则会报错

List<String> delIdsList = new ArrayList<>(Arrays.asList(ids.split(",")));

将list转换成以逗号分隔的字符串

String newIds = String.join(",", idsList);

获取对象list中的某个字段组成新的list

List<String> matchingIdList = list.stream().map(User::getMatchingId).collect(Collectors.toList());

将list对象中的某个字段转换成以逗号分隔的字符串

m.setIntelligenceListStr(userIntelDataList.stream().map(Intelligence::getIntelligenceName).collect(Collectors.joining(",")));

Collection转list

Collection<ComFile> comFiles;

comFiles.stream().collect(Collectors.toList())

 

3、mongo查询时间段的语句

mongo视图中的语句写法:

db.getCollection('dishonesty_system_error').find({errorTime:{$gte:1481526000000,$lt:1481529600000}})  (其中errorTime的类型为Long类型)

程序中的代码:

public List<ContactPersonBean> findAllContactpersonByTime(String start, String end) {
        Query query = new Query(Criteria.where("createTime").gte(Long.valueOf(start)).lt(Long.valueOf(end)));
        return mongoTemplate.find(query, ContactPersonBean.class);

    }

4、日期格式的相互转换

  /**
     * 日期格式的转换(String类型转long)
     *
     * @param date
     * @return
     */
    private static long dateFormat(String date) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = null;
        try {
            date1 = df.parse(date);
        } catch (Exception e) {
            logger.info("parse error");
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        return cal.getTimeInMillis();
    }


    /**
     * 日期格式的转换(long类型转日期)
     */
    private static String formatData(Long timestap) {
        Date date = new Date(timestap);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sdf.format(date);

    }

private static Log logger = LogFactory.getLog(DateUtil.class);
    
    /**
     * 把时间转换为秒数
     * 
     * @param time
     * hh小时mm分ss秒 ,hh时mm分ss秒 , mm分ss秒 ,ss秒
     * hh小时mm分钟ss秒 ,hh时mm分钟ss秒,mm分钟ss秒 ,30
     * @return 秒
     */
    public static int convertTimeToSecond(String time)
    {
        Pattern p = Pattern.compile("\\d*");
        Matcher m = p.matcher(time);
        
        List<Integer> times = new ArrayList<Integer>();
        while (m.find())
        {
            if (StringUtils.isNotBlank(m.group()))
            {
                times.add(Integer.valueOf(m.group()));
            }
        }
        switch (times.size())
        {
            case 0:
                return 0;
            case 1:
                // ss
                return times.get(0);
            case 2:
                // mm:ss
                return times.get(0) * 60 + times.get(1);
            case 3:
                // hh:mm:ss
                return times.get(0) * 60 * 60 + times.get(1) * 60 + times.get(2);
            default:
                return 0;
        }
        
    }
    
    /**
     * 把时间转换为秒数
     * 
     * @param time 00:00:04
     * @return 秒
     */
    public static int convertNomorTimeToSecond(String time)
    {
        int second = 0;
        try
        {
            String[] times = time.split(":");
            if (times.length == 3)
            {
                second += Integer.parseInt(times[0]) * 60 * 60;
                second += Integer.parseInt(times[1]) * 60;
                second += Integer.parseInt(times[2]);
            }
            else if (times.length == 2)
            {
                second += Integer.parseInt(times[0]) * 60;
                second += Integer.parseInt(times[1]);
            }
            else if (times.length == 1)
            {
                second = Integer.parseInt(time);
            }
        }
        catch (Exception e)
        {
            logger.error("parse nomore time fail! the time is " + time, e);
        }
        return second;
    }
    
    /**
     * 日期增加几天
     * @param datestr 日期
     * @param step 增加的天数,负数为减少调试
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String addDay(String datestr, int step)
    {
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date = formatter.parse(datestr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DATE, step);
            return formatter.format(calendar.getTime());
        }
        catch (ParseException e)
        {
            logger.error("add day error!datestr=" + datestr + "step=" + step, e);
        }
        return null;
    }
    
    /**
     * 月份增加几天
     * @param datestr 日期
     * @param step 增加的天数,负数为减少调试
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String addMonth(String datestr, int step)
    {
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date = formatter.parse(datestr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MONTH, step);
            return formatter.format(calendar.getTime());
        }
        catch (ParseException e)
        {
            logger.error("add day error!datestr=" + datestr + "step=" + step, e);
        }
        return null;
    }
    
    /**
     * 判断日期是否是最近一周
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isCurWeek(String date)
    {
        try
        {
            String curDate = getCurYearMonthDate();
            String lastDate = addDay(curDate, -7);
            
            int result1 = date.compareTo(curDate);
            int result2 = date.compareTo(lastDate);
            if (result1 <= 0 && result2 >= 0)
            {
                return true;
            }
        }
        catch (Exception e)
        {
            logger.error("isCurWeek error!date=" + date, e);
        }
        return false;
    }
    
    /**
     * 判断日期是否是最近一月
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isCurMonth(String date)
    {
        try
        {
            String curDate = getCurYearMonthDate();
            String lastDate = addMonth(curDate, -1);
            
            int result1 = date.compareTo(curDate);
            int result2 = date.compareTo(lastDate);
            if (result1 <= 0 && result2 >= 0)
            {
                return true;
            }
        }
        catch (Exception e)
        {
            logger.error("isCurMonth error!date=" + date, e);
        }
        return false;
    }
    
    /**
     * 判断日期是否是最近三月
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isCurThreeMonth(String date)
    {
        try
        {
            String curDate = getCurYearMonthDate();
            String lastDate = addMonth(curDate, -3);
            
            int result1 = date.compareTo(curDate);
            int result2 = date.compareTo(lastDate);
            if (result1 <= 0 && result2 >= 0)
            {
                return true;
            }
        }
        catch (Exception e)
        {
            logger.error("isCurThreeMonth error!date=" + date, e);
        }
        return false;
    }
    
    /**
     * 传入的日期是否在2个时间之间
     * @param date 需要判断的时间 HH:mm:ss
     * @param startTime 
     * @param endTime
     * @return 之间返回true
     * @see [类、类#方法、类#成员]
     */
    public static boolean isBetwenTime(String date, String startTime, String endTime)
    {
        try
        {
            if (date.length() > 8)
            {
                date = date.substring(date.length() - 8, date.length());
            }
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            Calendar cal0 = Calendar.getInstance();
            cal0.setTime(formatter.parse(date));
            String date0 = formatter.format(cal0.getTime());
            int result1 = date0.compareTo(startTime);
            int result2 = date0.compareTo(endTime);
            
            if (result1 > 0 && result2 < 0)
                return true;
            else
                return false;
        }
        catch (Exception e)
        {
            logger.error("parse time fail! the time is " + date, e);
        }
        return false;
    }
    
    /**
     * 判断日期是否是凌晨
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isEarlyMorning(String date)
    {
        return isBetwenTime(date, "00:00:00", "05:00:00");
    }
    
    /**
     * 判断日期是否是上午
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isMorning(String date)
    {
        return isBetwenTime(date, "05:00:00", "12:00:00");
    }
    
    /**
     * 判断日期是否是下午
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isNoon(String date)
    {
        return isBetwenTime(date, "14:00:00", "18:00:00");
    }
    
    /**
     * 判断日期是否是晚上
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isAfternoon(String date)
    {
        return isBetwenTime(date, "18:00:00", "22:00:00");
    }
    
    /**
     * 判断日期是否是深夜
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isNight(String date)
    {
        return isBetwenTime(date, "22:00:00", "23:59:59");
    }
    
    /**
     * 判断日期是否是周中
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isWeekday(String date)
    {
        try
        {
            Calendar cal = Calendar.getInstance();
            
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            
            cal.setTime(formatter.parse(date));
            int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (week == 1 || week == 2 || week == 3 || week == 4 || week == 5)
            {// 0代表周日,6代表周六
                return true;
            }
        }
        catch (Exception e)
        {
            logger.error("parse time fail! the time is " + date, e);
        }
        
        return false;
    }
    
    /**
     * 判断日期是否是周末
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isWeekend(String date)
    {
        try
        {
            Calendar cal = Calendar.getInstance();
            
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            
            cal.setTime(formatter.parse(date));
            int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (week == 6 || week == 0)
            {// 0代表周日,6代表周六
                return true;
            }
        }
        catch (ParseException e)
        {
            logger.error("parse time fail! the time is " + date, e);
        }
        
        return false;
    }
    
    
    /**
     * 获得年月
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return 秒
     */
    public static String getYearAndMonth(String date)
    {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat ymformatter = new SimpleDateFormat("yyyy-MM");
        try
        {
            Date sourceDate = formatter.parse(date);
            return ymformatter.format(sourceDate);
        }
        catch (ParseException e)
        {
            logger.error("parse date fail! the date is " + date, e);
        }
        return null;
    }
    
    /**
     * 获取简单的当前时间的日期字符串
     * 
     * @return
     */
    public static String getSimpDate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date());
    }
    
    /**
     * 获得当前时间
     * 
     * @return
     */
    public static String getCurDate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
    
    /**
     * 获得当前时间
     * 
     * @return
     */
    public static String getCurYearMonthDate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }
    
    /**
     * 把yyyy-MM-dd HH:mm:ss格式的字符串转换为日期对象
     * 
     * @return
     */
    public static Date convertNormalDate(String date)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            return sdf.parse(date);
        }
        catch (ParseException e)
        {
            logger.error("parse date to yyyy-MM-dd HH:mm:ss fail! the date is " + date);
        }
        return null;
    }
    
    /**
     * 获取yyyy-MM-dd HH:mm:ss格式的字符串的毫秒数
     * @param date
     * @return
     */
    public static Long getDateMillisecond(String date)
    {
        Date normalDate = convertNormalDate(date);
        
        if (null != normalDate)
        {
            return normalDate.getTime();
        }
        else
        {
            return null;
        }
    }
    
    /**
     * 判断日期是否是在N个月之内
     * @param yearMonth 需要判断的日期,格式为yyyyMM
     * @param month 几个月之内
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean contansYearMonth(String yearMonth, int month)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        try
        {
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(yearMonth));
            cal.add(Calendar.MONTH, month);
            
            if (cal.getTimeInMillis() < sdf.parse(sdf.format(new Date())).getTime())
            {
                return false;
            }
        }
        catch (ParseException e)
        {
            logger.error("parse yyyyMM fail! the yearMonth is " + yearMonth + "month:" + month, e);
        }
        return true;
    }

 

4、对两个list合并,并且去重

public static List<ContactPersonBeanSql> getNewContactPerson(List<ContactPersonBeanSql> dataBigList, List<ContactPersonBeanSql> mysqlList) {
        Map<String, ContactPersonBeanSql> map = new HashMap<>();
        for (ContactPersonBeanSql contactPersonBeanSql : dataBigList) {
            map.put(contactPersonBeanSql.getContact_phone(), contactPersonBeanSql);
        }
        for (ContactPersonBeanSql contactPersonBeanSql : mysqlList) {
            map.put(contactPersonBeanSql.getContact_phone(), contactPersonBeanSql);
        }
        ArrayList<ContactPersonBeanSql> contactPersonBeanSqls = new ArrayList<>();
        for (Map.Entry<String, ContactPersonBeanSql> entry : map.entrySet()) {
            contactPersonBeanSqls.add(entry.getValue());
        }
        return contactPersonBeanSqls;

    }

5、将json格式的文本读取并解析

 

String json = FileCopyUtils.copyToString(new FileReader(new File("D:/test.txt")));
List<Statics> list = new Gson().fromJson(json, new TypeToken<List<Statics>>() {
}.getType());

 

6、(将json字符串转换成Map<String,Object>)

 

 

 
 
import com.fasterxml.jackson.databind.ObjectMapper;
 
import com.google.gson.*;
import java.util.*;
import java.util.Map.Entry;
public static Gson defaultGson = new Gson();
public static Gson serializeNulls = new GsonBuilder().serializeNulls().create();
public static ObjectMapper objectMapper = new ObjectMapper();

/**
 * 获取JsonObject
 *
 * @param json
 * @return
 */
public static JsonObject parseJson(String json) {
    JsonParser parser = new JsonParser();
    JsonObject jsonObj = parser.parse(json).getAsJsonObject();
    return jsonObj;
}

/**
 * 根据json字符串返回Map对象
 *
 * @param json
 * @return
 */
public static Map<String, Object> toMap(String json) {
    return JsonToMap.toMap(JsonToMap.parseJson(json));
}


@SuppressWarnings("unchecked")
public static Map<String, Object> toMapV2(String json) {
    try {
        return objectMapper.readValue(json, Map.class);
    } catch (IOException e) {
        TryYtils.doThrow(e);
    }
    return new LinkedHashMap<>();
}


/**
 * 将JSONObjec对象转换成Map-List集合
 *
 * @param json
 * @return
 */
public static Map<String, Object> toMap(JsonObject json) {
    Map<String, Object> map = new HashMap<String, Object>();
    Set<Entry<String, JsonElement>> entrySet = json.entrySet();
    for (Iterator<Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext(); ) {
        Entry<String, JsonElement> entry = iter.next();
        String key = entry.getKey();
        Object value = entry.getValue();
        if (value instanceof JsonArray) {
            map.put(key, toList((JsonArray) value));
        } else if (value instanceof JsonObject) {
            map.put(key, toMap((JsonObject) value));
        } else {
            map.put(key, value);
        }
    }
    return map;
}

/**
 * 将JSONArray对象转换成List集合
 *
 * @param json
 * @return
 */
public static List<Object> toList(JsonArray json) {
    List<Object> list = new ArrayList<Object>();
    for (int i = 0; i < json.size(); i++) {
        Object value = json.get(i);
        if (value instanceof JsonArray) {
            list.add(toList((JsonArray) value));
        } else if (value instanceof JsonObject) {
            list.add(toMap((JsonObject) value));
        } else {
            list.add(value);
        }
    }
    return list;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值