如何从当月开始订购月份名称

时间:2017-08-11 14:02:13

标签: java sorting

假设这是用于存储月份的数组,

String months[] = {"January", "February", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"};

我已使用此方法获取当月

int monthName=calendar.get(Calendar.MONTH);

从当前月份开始,将数组重新排序为新数组或arraylist的最佳方法是什么。

Ex:当前月份是八月,所以所需的数组或Arraylist将是

months[] = {"August", "September", "October", "November",
            "December", "January", "February", "March", "April",
            "May", "June", "July"};

2 个答案:

答案 0 :(得分:6)

对于那些很快或以后想要使用java 8执行相同操作的人来说,只是另一种选择:)

List<Month> myMonth = Arrays.asList(Month.values());

Collections.rotate(myMonth, 1 - LocalDate.now().getMonthValue());

输出:

  

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

答案 1 :(得分:5)

使用Java 8 Month.values()Collections.rotate()

int monthOffset = LocalDate.now().getMonth().getValue() - 1;
List<Month> months = Arrays.asList(Month.values());
Collections.rotate(months, -monthOffset);
System.out.println(months);

打印:

[AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER, JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY]