将DayOfWeek集合的元素旋转为区域设置定义的顺序

fjaof16o  于 2022-10-22  发布在  Java
关注(0)|答案(2)|浏览(122)

假设我们可以通过使用Locale进行软编码来确定一周的第一天:

DayOfWeek firstDayOfWeek = WeekFields.of( Locale.US ).getFirstDayOfWeek() ;  // Sunday-Saturday.

…并且考虑到Java带有一个内置的枚举,定义了一周中的几天,DayOfWeek

DayOfWeek[] dows = DayOfWeek.values() ;  // Monday-Sunday

我们如何创建另一个数组或元素列表,这些元素是按照指定区域设置定义的顺序重新排列的DayOfWeek枚举对象?

h43kikqp

h43kikqp1#

tl;博士

Collections.rotate( 
    new ArrayList<> ( List.of( DayOfWeek.values() ) ) ,   // Actually, you would instantiate elsewhere and pass here.
    DayOfWeek.MONDAY.ordinal() - WeekFields.of( Locale.US ).getFirstDayOfWeek().ordinal()  
)

详细信息

幸运的是,你不需要自己做列表轮换工作。Collections实用程序类提供了rotate方法。将列表与偏移量一起传递。
引用Javadoc:
将指定列表中的元素旋转指定距离。调用此方法后,索引i处的元素将是之前索引(i-distance)mod list处的元素。size(),用于0和list之间的所有i值。size()-1,包括。(此方法对列表的大小没有影响。)
例如,假设列表包含[t,a,n,k,s]。调用Collections之后。rotate(list,1)(或Collections.rotate,-4)),list将包含[s,t,a,n,k]。

final List< DayOfWeek > iso8601 = List.of( DayOfWeek.values() ) ;  // Monday-Sunday, defined in ISO 8601 standard.
List< DayOfWeek > localeOrder = new ArrayList<>( iso8601 ) ;       // Duplicate the list of DayOfWeek objects.
Locale locale = Locale.US ;
DayOfWeek localeFirstDayOfWeek = WeekFields.of( locale ).getFirstDayOfWeek() ;  // Sunday-Saturday.
int distance = DayOfWeek.MONDAY.ordinal() - localeFirstDayOfWeek.ordinal() ;
Collections.rotate( localeOrder , distance ) ;

转储到控制台。

System.out.println( iso8601 ) ;
System.out.println( localeOrder ) ;
System.out.println( distance ) ;

请参阅code run at Ideone.com
[周一、周二、周三、周四、周五、周六、周日]
[星期日、星期一、星期二、星期三、星期四、星期五、星期六]
-6
或者更简单地说:

List< DayOfWeek > localeOrder = new ArrayList< DayOfWeek > ( List.of( DayOfWeek.values() ) ) ;   
Collections.rotate( 
    localeOrder , 
    DayOfWeek.MONDAY.ordinal() - WeekFields.of( Locale.US ).getFirstDayOfWeek().ordinal()  
) ;

请参阅此code run at Ideone.com
[星期日、星期一、星期二、星期三、星期四、星期五、星期六]

ewm0tg9j

ewm0tg9j2#

以下是如何使用List.subList()Stream.concat()来完成此操作。

核心理念

旋转列表可由两部分构成:

  • 从一周的第一天到星期天(含);
  • 从周一到一周的第一天(不含)。如果一周的第一天是星期一,那么第二部分将是空的。

这就是实现的样子:

DayOfWeek firstDayOfWeek = WeekFields.of(Locale.US).getFirstDayOfWeek();   // the first Day of Week

List<DayOfWeek> initial = new ArrayList<>(EnumSet.allOf(DayOfWeek.class)); // initial list of Days of Week ordered according to ISO-8601

List<DayOfWeek> rotated = Stream.concat(
    initial.subList(firstDayOfWeek.ordinal(), DayOfWeek.SUNDAY.ordinal() + 1).stream(), // from the firstDayOfWeek to Sunday inclusive
    initial.subList(DayOfWeek.MONDAY.ordinal(), firstDayOfWeek.ordinal()).stream()      // from Monday to the firstDayOfWeek exclusive
).toList();

rotated.forEach(System.out::println); // printing the result
  • 输出:*
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

A link to Online Demo

相关问题