有如下日期:
“2021-11-09”、“2021-11-20”、“2021-12-16”、
“2022-03-11”、“2022-03-20”、“2022-05-22”。
要求输出的结果为:2021年11、12月,2022年03、05月
实现代码如下:
package com.zo.next;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.Null;
public class Test {
public static void main(String[] args) {
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
Map<String, Object> m1 = new HashMap<String, Object>();
m1.put("date", "2021-11-09");
list.add(m1);
m1 = new HashMap<String, Object>();
m1.put("date", "2021-11-20");
list.add(m1);
m1 = new HashMap<String, Object>();
m1.put("date", "2021-12-16");
list.add(m1);
m1 = new HashMap<String, Object>();
m1.put("date", "2022-03-11");
list.add(m1);
m1 = new HashMap<String, Object>();
m1.put("date", "2022-03-20");
list.add(m1);
m1 = new HashMap<String, Object>();
m1.put("date", "2022-05-22");
list.add(m1);
//结果 2021年11、12月,2022年3、5月
List<Map<String, Object>> l = new ArrayList<Map<String,Object>>();// [{"年": "2021", "月": "11"}, {"年": "2021", "月": "12"}]
for (int i = 0; i < list.size(); i++) {
String dateString = ((String)list.get(i).get("date")) .substring(0, 7);
String yearString = dateString.split("-")[0];
String monthString = dateString.split("-")[1];
int x = 0;
for (int j = 0; j < l.size(); j++) {
if(yearString.equals((String)l.get(j).get("年")) && monthString.equals((String)l.get(j).get("月"))){
x++;
}
}
if(x == 0){
Map<String, Object> m2 = new HashMap<String, Object>();
m2.put("年", yearString);
m2.put("月", monthString);
l.add(m2);
}
}
StringBuilder result = new StringBuilder();
Map<String, Object> m3 = new HashMap<String, Object>();
for (int i = 0; i < l.size(); i++) {
if(m3.get("年") == null ){
result = result.append((String)l.get(i).get("年")).append("年").append((String)l.get(i).get("月"));
}else if( ((String)m3.get("年")).equals( (String)l.get(i).get("年") ) && !((String)m3.get("月")).equals( (String)l.get(i).get("月") )){ // 同年不同月
result = result.append("、").append((String)l.get(i).get("月"));
}else if(!((String)m3.get("年")).equals( (String)l.get(i).get("年") )){ //不同年
result = result.append("月,").append((String)l.get(i).get("年")).append("年").append((String)l.get(i).get("月"));
}
m3 = l.get(i);
}
result = result.append("月");
System.err.println(result);
}
}