在这里插入代码片
/**
* 对list数组分组 [201901,201902,201906,201908] ->[201901,201902], [201906], [201908]
* @return
*/
public static Map<Integer,List<String>> getGroups(List<String> list){
//月份补全 201902-201905 ->[201902,201903,201904,201905]
List<String> middleDateList = DateUtil.getMiddleDateList(list.get(0), list.get(list.size() - 1));
System.out.println(middleDateList);
//差集
List<String> reduce1 = middleDateList.stream().filter(item -> !list.contains(item)).collect(toList());
System.out.println("差集:" + reduce1);
Map<Integer, List<String>> map = new HashMap<>();
if (reduce1.size() > 0) {
//第一段
if (list.get(0).equals(DateUtil.getDateByMonth(reduce1.get(0), -1))) {
map.put(0, Arrays.asList(list.get(0)));
} else {
map.put(0, Arrays.asList(list.get(0), DateUtil.getDateByMonth(reduce1.get(0), -1)));
}
//后续分段
for (int i = 0; i < reduce1.size(); i++) {
String afterMonth = DateUtil.getDateByMonth(reduce1.get(i), 1);
if (i == reduce1.size() - 1) {
if (afterMonth.equals(list.get(list.size() - 1))) {
map.put(i + 1, Arrays.asList(list.get(list.size() - 1)));
} else {
if (!list.contains(afterMonth)) {
map.put(i + 1, Arrays.asList(list.get(list.size() - 1)));
}else{
map.put(i + 1, Arrays.asList(afterMonth, list.get(list.size() - 1)));
}
}
} else {
String beforeMonth = DateUtil.getDateByMonth(reduce1.get(i + 1), -1);
if (afterMonth.equals(beforeMonth)) {
map.put(i + 1, Arrays.asList(afterMonth));
} else {
//若list中不含间隔大于2 1,3,6 或1 3 10
if (!list.contains(afterMonth) || !list.contains(beforeMonth)) {
continue;
} else {
map.put(i + 1, Arrays.asList(afterMonth, beforeMonth));
}
}
}
}
} else {
//无差集,则无不同
map.put(0, Arrays.asList(list.get(0), list.get(list.size() - 1)));
}
return map;
}
/**
* 获取起始日期到结束日期列表 如:201902-201905 [201902,201903,201904,201905]
* @param startDateStr
* @param endDateStr
* @return
*/
public static List<String> getMiddleDateList(String startDateStr, String endDateStr) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
List<String> durationStrList = new ArrayList<>();
try {
Date startDate = simpleDateFormat.parse(startDateStr);
Date endDate = simpleDateFormat.parse(endDateStr);
String durationStr = DurationFormatUtils.formatPeriod(startDate.getTime(), endDate.getTime(), "MM");
if(StringUtils.isNotBlank(durationStr)){
durationStrList.add(startDateStr);
for(int i=0; i<Integer.parseInt(durationStr); i++){
startDateStr = getNextMonth(startDateStr);
durationStrList.add(startDateStr);
}
}
} catch (ParseException e) {
log.error(String.format("获取时间列表失败: 起始日期-%s,结束日期-%", startDateStr, endDateStr));
e.printStackTrace();
}
return durationStrList;
}
java对年月分组 [201901,201902,201904,201906]->[[201901,201902],[201904],[201906]]
最新推荐文章于 2022-03-02 11:53:52 发布