1. 獲取當前月份的所有日期
/**
* get all date of specified month(date format)
*
* @param date
*/
public static void printDays(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// get total days of month
int daysOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
// set 1st day of month,like 2019-03-01
calendar.set(Calendar.DAY_OF_MONTH, 1);
for (int i = 0; i < daysOfMonth; i++, calendar.add(Calendar.DATE, 1)) {
System.out.println(calendar.getTime());
}
}
2. 生成指定日期段的每一天日期:
public static List<Date> listDays(Date startDate, Date endDate) {
List dateList = new ArrayList();
dateList.add(startDate);
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
while (endDate.after(startCalendar.getTime())) {
startCalendar.add(Calendar.DAY_OF_MONTH, 1);
dateList.add(startCalendar.getTime());
}
return dateList;
}
注:如果是指定時段的每個月,只需要將步進值的單位改爲月份即可(Calendar.DAY_OF_MONTH
-> Calendar.MONTH
),根據需要進行格式化即可。
3. 合併多個Map
對象
merge()
函數可以很方便的進行Map
對象的合併。下面是將map1
和map2
合併到一個新的Map
對象midMap
中:
// 從map1複製出一個新對象,用於存放合併結果
Map<String, Integer> map = new HashMap<>(map1);
// 合併,key不變,value直接相加
map2.forEach((key, value) -> map.merge(key, value, (otherKey, otherValue) -> value + otherValue));
4. List
轉Map
Map<String, Integer> dateCountsMap = dateAndCounts.stream().collect(Collectors.toMap(DateAndCount::getDate, DateAndCount::getCount));