来自日历的getDisplayNames提供未分类的月份

时间:2017-06-20 15:42:25

标签: java calendar

我从Calendar这样成功地完成了这样的月份:

monthMap = calendar.getDisplayNames(Calendar.MONTH, Calendar.LONG, Locale.getDefault());

但几个月似乎:

enter image description here

无论如何,我会将它们作为1月1日的索引0,然后是其余部分吗?

我会对列表进行排序,但没有排序标准。

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

您正在获取完全未排序的地图,因此您需要按值

实施排序条件
 Map<String, Integer> map = Calendar.getInstance().getDisplayNames(Calendar.MONTH, Calendar.LONG,
            Locale.getDefault());
 List<Entry<String, Integer>> months = new ArrayList<>(map.entrySet());
 months.sort((e1, e2) -> Integer.compare(e1.getValue(), e2.getValue()));
 months.stream().forEach(System.out::println);

或者你可以考虑使用 java8 之后的java.time幂,因为我们都应该停止学习旧的坏/邪恶/破坏的java日历:

Month month = Month.JUNE;

for (Month m : Month.values()) {
    System.out.println(m);
}

或保持与java8的连贯性

Arrays.stream(Month.values()).forEach(System.out::println);

答案 1 :(得分:2)

首先,我建议您停止使用Calendar(正如this answer所建议的那样)。

旧类(DateCalendarSimpleDateFormat)有lots of problemsdesign issues,并且它们被新API取代

如果您使用 Java 8 ,请考虑使用new java.time API。它更容易,less bugged and less error-prone than the old APIs

如果您正在使用 Java&lt; = 7 ,则可以使用ThreeTen Backport,这是Java 8新日期/时间类的绝佳后端。对于 Android ThreeTenABP(更多关于如何使用它here)。

以下代码适用于两者。 唯一的区别是包名称(在Java 8中为java.time而在ThreeTen Backport(或Android的ThreeTenABP中)为org.threeten.bp),但类和方法名称是一样的。

对我而言,不清楚您是否需要包含月份名称的列表或包含月份的地图(将月份名称作为键,将数字作为值)。无论如何,这里是两个代码(假设默认语言环境是英语):

// created the sorted list
List<String> months = new ArrayList<>();
for (Month m : Month.values()) {
    months.add(m.getDisplayName(TextStyle.FULL, Locale.getDefault()));
}
System.out.println("list: " + months);

// create the map (using LinkedHashMap, as it preserves the insertion order)
Map<String, Integer> map = new LinkedHashMap<>();
int i = 0;
for (String m : months) {
    map.put(m, i++);
}
System.out.println("map: " + map);

输出将是:

  

列表:[1月,2月,3月,4月,5月,6月,7月,8月,9月,10月,11月,12月]

     

map:{January = 0,February = 1,March = 2,April = 3,May = 4,June = 5,July = 6,August = 7,September = 8,October = 9,November = 10,腊= 11}

答案 2 :(得分:1)

您只需找到一种方法对其进行排序。你有可能得到一个HashMap,它不承诺任何订单。

Map<String, Integer> map = Calendar.getInstance()
    .getDisplayNames(Calendar.MONTH, Calendar.LONG, Locale.getDefault());

List<Entry<String, Integer>> entries = 
    new ArrayList<Entry<String, Integer>>(map.entrySet()); 

//This line sorts entries by key.
Collections.sort(entries, 
    (entry1, entry2) -> entry1.getKey().compareTo(entry2.getKey()));

//Now the list will be sorted:
for(Entry<String, Integer> entry: entries) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

对于数字排序,您可以将对sort的调用替换为

Collections.sort(entries, 
    (entry1, entry2) -> Integer.valueOf(entry1.getKey()).compareTo(Integer.valueOf(entry2.getKey())));