Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<DayOfWeek> in localized order

We have the DayOfWeek enum defining the days of the week in standard ISO 8601 order.

I want a List of those objects in the order appropriate to a Locale.

We can easily determine the first day of the week for locale.

Locale locale = Locale.CANADA_FRENCH ;
DayOfWeek firstDayOfWeek =  WeekFields.of( locale ).getFirstDayOfWeek() ;

Set up the List.

List< DayOfWeek > dows = new ArrayList<>( 7 ) ;  // Set initial capacity to 7, for the seven days of the week.
dows.add( firstDayOfWeek ) ;

➥ To add the other six days of the week to that list, what is the simplest/shortest/most elegant approach?

like image 626
Basil Bourque Avatar asked May 20 '19 03:05

Basil Bourque


1 Answers

You can use the plus method of DayOfWeek.

The calculation rolls around the end of the week from Sunday to Monday.

Increment numbers with IntStream and its range method (inclusive start, exclusive end).

Locale locale = Locale.CANADA_FRENCH;
DayOfWeek firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();

List<DayOfWeek> dows = IntStream.range(0, 7)
        .mapToObj(firstDayOfWeek::plus)
        .collect(Collectors.toList());
like image 194
Kartik Avatar answered Nov 18 '22 16:11

Kartik