gpt4 book ai didi

java - 对列表中的 MMM-yyyy 进行排序,而不转换为日期

转载 作者:行者123 更新时间:2023-12-01 17:22:47 25 4
gpt4 key购买 nike

如何在不将字符串转换为 Date 对象的情况下对 MonthYear 列表进行排序?我无法在这里应用逻辑。

public class SortDates {

public static void main(String[] args) {

String[] monthName = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL",
"AUG", "SEP", "OCT", "NOV", "DEC" };

List<String> monthYear = new ArrayList<String>();

monthYear.add("JAN-1999");
monthYear.add("JUN-2009");
monthYear.add("MAR-2003");
monthYear.add("JAN-1998");
monthYear.add("NOV-2013");

}

}

最佳答案

我首先会在枚举中描述月份:

enum Month{ JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

然后您就可以轻松实现自己的比较器:

public static class MyComparator implements Comparator<String>{
@Override
public int compare(String s1, String s2) {

//If s1="JAN-1999", parts1[0]="JAN", parts1[1]="1999"
String[] parts1=s1.split("-");
//Month.valueOf("JAN") converts "JAN" to Month.JAN
int m1 = Month.valueOf(parts1[0]).ordinal();
int year1 = Integer.valueOf(parts1[1]);

String[] parts2=s2.split("-");
int m2 = Month.valueOf(parts2[0]).ordinal();
int year2 = Integer.valueOf(parts2[1]);

return ...//Here, compare year1 to year2 and if necessary, m1 and m2
//You can also return (100*year2+m2) - (100*year1+m1)
}
}

然后用它来排序:

Collections.sort(monthYear, new MyComparator());

关于java - 对列表中的 MMM-yyyy 进行排序,而不转换为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17324852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com