Search code examples
javadayofweekjava-time

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?


Solution

  • 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());