Java 常用功能代碼片段(獲取當前年份、SpringBoot資源讀取方式和類資源讀取方式、Date日期大小比較、List 集合刪除重複數據)

1、獲取當前年份

實現方式一:SimpleDateFormat + Date

public static String getCurrentYear(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date = new Date();
        return sdf.format(date);
}

實現方式二:Calendar

public static String getCurrentYear() {
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        return year;
}

2、讀取資源的實現方式:springboot + 類

實現方式一:spring Boot 讀取資源方式:

FileInputStream inputStream = new FileInputStream(ResourceUtils.getFile("classpath:***.xml")
注意:如果是在多模塊java項目中不推薦使用,因爲ResourceUtils 加載資源類是依據當前執行的線程獲取,如果你編寫的模塊要被打包成jar 包供其他業務模塊的調用,會導致讀取的資源文件無法找到,所以建議不推薦使用。

實現方式二: 當前類讀取資源方式

FileInputStream inputStream = (FileInputStream)Confing.class.getClassLoader().getResourceAsStream(xmlName)
注意:推薦使用

3、比較日期大小

                // 最近一次錯誤登記日期
					Date lockDate = Collections.max(
						list.stream().map(item ->{
							JSONObject jsonObject = JSONObject.parseObject(item);
							return new Date((long)jsonObject.get("createdDt"));
						}).collect(Collectors.toList())
					);
					// 解鎖日期
					Calendar unLockDate = Calendar.getInstance();
					unLockDate.setTime(lockDate);
					unLockDate.add(Calendar.MINUTE, 5);
					// 判斷解鎖時間是否當前時間之前 
					if(unLockDate.getTime().getTime() > new Date().getTime()){
						return false;
					} else {
						return true;
					}

 

4、Java 8 Stream List集合刪除重複元素

        List<Integer> list = Lists.newArrayList(1, 2, 2, 2, 5);
        list = list.stream().distinct().collect(Collectors.toList());

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章