List<DayOfWeek> in localized order
Asked Answered
T

2

6

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?

Tavish answered 20/5, 2019 at 3:4 Comment(0)
W
9

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());
Weihs answered 20/5, 2019 at 3:37 Comment(1)
Perfect. I never noticed that method. That beats ( ( firstDayOfWeek.getValue() + i - 1 ) % 7 + 1 ) in a for ( int i = 0 ; i < 7 ; i++ ) loop.Tavish
O
2

My solution in Kotlin:

fun sortedDaysOfWeek(locale: Locale = Locale.getDefault()): List<DayOfWeek> {
     val firstDayOfWeek = WeekFields.of(locale).firstDayOfWeek

     return DayOfWeek.values().partition { it == firstDayOfWeek }
                              .let{ it.first + it.second }
}
Overstride answered 9/3, 2023 at 16:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.