I have an EnumSet
public static Set<T> getTypes() {
return EnumSet.of(
TYPE_1,
TYPE_2,
TYPE_3
);
}
And i want to get the values from it with a getter method
When i try to get the values in my program with a foreach loop they always come in wrong order. Is there a way to get them in correct order as written above? Thanks!
CodePudding user response:
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
CodePudding user response:
Set is not keeping sort, so rather than it use List like:
public static List<T> getTypes() {
return Arrays.asList(
TYPE_1,
TYPE_2,
TYPE_3
);
}
CodePudding user response:
Whenever you want a Set to keep the order in which elements were added, there's one obvious choice: LinkedHashSet. That's the only Set implementation in the JDK that explicitly states that it preserves insertion order (unless you tell it to use last-access order).
