将日期按照年月升序输出

发布时间 2023-04-26 14:46:16作者: 孔小爽
import java.util.ArrayList;
import java.util.*;
import java.util.regex.*;
import java.util.stream.Collectors;

// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Main {
    public static void main(String[] args) {
        List<String> years = new ArrayList<>();
        years.add("2023年04月");
        years.add("2023年03月");
        years.add("2023年02月");
        years.add("2023年01月");
        years.add("2021年02月");
        years.add("2021年03月");
        years.add("2021年04月");
        years.add("2021年05月");
        years.add("2021年06月");
        years.add("2021年07月");
        years.add("2021年08月");
        years.add("2021年09月");
        List<YearMonth> list = years.stream().map(YearMonth::new).sorted().collect(Collectors.toList());
        // 只要最大日期前12个
        for(int i=list.size()-12; i<list.size(); ++i) {
            System.out.println(list.get(i));
        }
    }
    static class YearMonth implements Comparable<YearMonth> {
        private static Pattern pattern = Pattern.compile("(\\d{4})年(\\d{1,2})月");
        private String origin;
        private int year;
        private int month;
        public YearMonth(String origin) {
            this.origin = origin;
            Matcher matcher = pattern.matcher(origin);
            if(matcher.find()) {
                this.year = Integer.parseInt(matcher.group(1));
                this.month = Integer.parseInt(matcher.group(2));
            }
        }

        @Override
        public String toString() {
            return origin;
        }

        /**
         * 从小到大排序
         * @param o the object to be compared.
         * @return
         */
        @Override
        public int compareTo(YearMonth o) {
            if(this.year > o.year) {
                return 1;
            }
            if(this.year < o.year) {
                return -1;
            }
            if(this.month>o.month) {
                return 1;
            }
            if(this.month<o.month) {
                return -1;
            }
            return 0;
        }
    }
}

输出结果: