The order of elements in the EnumSet
is the same as the natural ordering of the enum constants (i.e. the order of their declaration).
EnumSet
.of(DayOfWeek.SATURDAY, DayOfWeek.FRIDAY, DayOfWeek.THURSDAY)
.forEach(System.out::println);
Output:
THURSDAY
FRIDAY
SATURDAY
If you need the order that differs from the natural ordering, you can switch to using a List
instead of a Set
:
List
.of(DayOfWeek.SATURDAY, DayOfWeek.FRIDAY, DayOfWeek.THURSDAY)
.forEach(System.out::println);
Output:
SATURDAY
FRIDAY
THURSDAY
Or if you need Set
as a type, you can introduce a property responsible for ordering in your enum
and make use of the TreeSet
providing a Comparator
which is based on this property.
Consider the following dummy enum
:
public enum MyEnum {
ONE(3), TWO(2), THREE(1);
private int order;
MyEnum(int order) {
this.order = order;
}
public int getOrder() {
return order;
}
}
Example of storing the enum members into a TreeSet
:
Stream.of(MyEnum.ONE, MyEnum.TWO, MyEnum.THREE)
.collect(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(MyEnum::getOrder))
))
.forEach(System.out::println);
Output:
THREE
TWO
ONE