簡體   English   中英

如何將整數數組轉換為枚舉數組?

[英]How to convert an array of integers to array of enums?

我有一個整數數組,需要將它轉換為枚舉數組。

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;
}

...但我希望有更直接的方法來進行轉換(否則在我的代碼中,首先使用枚舉是沒有意義的)。

是一個關於將單個整數轉換為枚舉值的問題。

您需要使用循環或流來迭代整數的輸入數組,並將每個映射到Color實例。 嘗試這個:

int[] array = getArrayOfInts();
Color[] colors = Arrays.stream(array)
            .mapToObj(i -> convertIntToColor(i))
            .filter(Objects::nonNull)
            .toArray(Color[]::new);

這取決於你的foo數組中的內容。 如果它是枚舉的ordinal ,那么這樣簡單就足夠了。

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));
}

版畫

[APPLE,ORANGE,ORANGE,BANANA]

等效的streams將是這樣的:

    my_enum[] es = Arrays.stream(foo)
            .mapToObj(i -> my_enum.values()[i])
            .toArray(my_enum[]::new);

這一行代碼將返回對象數組,您可以通過arr [0]訪問枚舉

Object[] arr = Arrays.stream(my_enum.values()).map(x->x).toArray();

但我希望有更直接的方式來實現這種轉換

你沒有選擇。 因為你有int值,你想將它們轉換為枚舉值。
因此,對於每個int你必須找到對應的枚舉值,無論如何。

在聲明中使用枚舉的順序有一個更直接的方法
但它是一種非常容易出錯的方法,它假定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]

最好使用List with Java,但有轉換工具。 也更喜歡使用Java約定:MyEnum。

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);

    }


};

使用array和int使得使用流變得復雜,主要部分是從int到enum轉換使用: i->MyEnum.values()[i]要使用此函數轉換,您需要可以從流中訪問map方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM