我有一个整数数组,需要将其转换为枚举数组。
enum my_enum {
APPLE, BANANA, ORANGE;
int getColorAsInt() { ... }
};
int[] foo = some_method_i_cannot_modify();
my_enum[] bar = ??? ( foo );
最简单的方法是什么?
在这里,我找到了一种将单个整数转换为枚举值的方法(他们在示例中使用了Color
枚举(:
public static Color convertIntToColor(int iColor) {
for (Color color : Color.values()) {
if (color.getColorAsInt() == iColor) {
return color;
}
}
return null;
}
...但是我希望有一种更直接的方法来进行转换(否则在我的代码中,首先使用枚举是没有意义的(。
这是一个关于将单个整数转换为枚举值的问题。
这取决于您的foo
数组中的内容。如果这是枚举的ordinal
s,那么这样简单的东西就足够了。
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));
}
打印
[苹果,橙色,橙色,香蕉]
streams
等效物将是:
my_enum[] es = Arrays.stream(foo)
.mapToObj(i -> my_enum.values()[i])
.toArray(my_enum[]::new);
您需要使用循环或流通过整数的输入阵列进行迭代,然后将每个阵列映射到Color
实例。尝试以下操作:
int[] array = getArrayOfInts();
Color[] colors = Arrays.stream(array)
.mapToObj(i -> convertIntToColor(i))
.filter(Objects::nonNull)
.toArray(Color[]::new);
这一行代码将返回对象的数组,您可以访问枚举由ARR [0]
Object[] arr = Arrays.stream(my_enum.values()).map(x->x).toArray();
,但我希望有一种更直接的方法来进行转换
您没有选择。由于您具有int
值,并且要将它们转换为枚举值。
因此,对于每个int
S,您一定需要找到与与之相对应的枚举值。
您的声明中使用了枚举的顺序
但这是一个非常容易出错的方法,它假设int值开始为0,并以1。
如果是您的 enum
,则当然可以给它映射。
public enum MyEnum {
APPLES(10), ORANGES(20);
private int asInt;
private MyEnum(int val) {
asInt = val;
}
public int getIntValue() { return asInt; }
static final Map<Integer, MyEnum> mapping = new HashMap();
static {
for (MyEnum e : MyEnum.values()) {
mapping.put(e.getIntValue(), e);
}
}
static MyEnum fromInteger(int val) {
return mapping.get(val);
}
}
我会制作一个地图,一个从那里取映射的值。当然,使用自己的ID大于序数,但要显示一个想法:
enum Color {
RED, GREEN, BLUE;
public static Color[] create(int[] ids) {
Map<Integer, Color> colors = Arrays.stream(Color.values())
.collect(Collectors.toMap(Enum::ordinal, Function.identity()));
return Arrays.stream(ids)
.mapToObj(colors::get)
.filter(Objects::nonNull)
.toArray(Color[]::new);
}
};
public static void main(String[] args) {
int[] foo = new int[]{0,1,2};
System.out.println(Arrays.toString(Color.create(foo)));
}
输出
[RED, GREEN, BLUE]
最好使用Java在列表上工作,但是有转换工具。也更喜欢使用Java惯例:肌部。
enum MyEnum {
APPLE, BANANA, ORANGE;
public static void main(String[] arg) {
int[] foo = new int[] { 2, 0, 1 };
MyEnum[] bar = Arrays.stream(foo).boxed().map(
i->MyEnum.values()[i]
).toArray(MyEnum[]::new);
}
};
使用数组和int
使使用流变得复杂,主要部分是从INT到枚举转换:i->MyEnum.values()[i]
要使用此功能转换,您需要从流中访问的地图方法。