I have an array of integers and need to convert it to an array of enums.
enum my_enum {
APPLE, BANANA, ORANGE;
int getColorAsInt() { ... }
};
int[] foo = some_method_i_cannot_modify();
my_enum[] bar = ??? ( foo );
What is the easiest way to do that?
Here I found a way to convert a single integer to an enum value (they are using a Color
enum in their example):
public static Color convertIntToColor(int iColor) {
for (Color color : Color.values()) {
if (color.getColorAsInt() == iColor) {
return color;
}
}
return null;
}
... but I hope there is a more direct way to do that conversion (otherwise in my code it doesnt make sense to use an enum in the first place).
Here is a SO question about converting a single integer to enum value.
It depends on what is in your foo
array. If it is the ordinal
s of the enums then something as simple as this should suffice.
enum my_enum { APPLE, BANANA, ORANGE };
int[] foo = {0,2,2,1};
public void test(String[] args) {
my_enum[] bar = new my_enum[foo.length];
for (int i = 0; i < foo.length; i++) {
bar[i] = my_enum.values()[foo[i]];
}
System.out.println(Arrays.toString(bar));
}
prints
[APPLE, ORANGE, ORANGE, BANANA]
A streams
equivalent would be something like:
my_enum[] es = Arrays.stream(foo)
.mapToObj(i -> my_enum.values()[i])
.toArray(my_enum[]::new);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments