使用Java 8 Streams如何将Enum对象数组转换为另一个Enum数组

时间:2019-02-14 21:50:00

标签: java java-8 java-stream

使用Java 8 Streams如何将枚举对象数组转换为另一个枚举对象数组

类结构

 enum QUESTIONS {
        CONTACT_QUESTION,
        ADDRESS_QUESTION,
        WORK_QUESTION
    };

 enum CODES {
       CQ,
       AQ,
       WQ
    };

输入

CODES[] firstSet_Short = {CODES.CQ, CODES.AQ} 

输出

QUESTIONS[] firstSet_Long = {QUESTIONS.CONTACT_QUESTION, QUESTIONS.ADDRESS_QUESTION}

1 个答案:

答案 0 :(得分:1)

我在这里匹配C***_Q***之类的代码的缩写:

CODES[] firstSet_Short = {CODES.CQ, CODES.AQ};

List<QUESTIONS> result = Arrays.stream(firstSet_Short)
        .map(c -> Arrays.stream(QUESTIONS.values())
                .filter(q -> q.toString().matches(c.toString().charAt(0) + ".+_" + c.toString().charAt(1) + ".+"))
                .findFirst().orElse(null))
        .collect(Collectors.toList()); //or .toArray(QUESTIONS[]::new); if you want array

System.out.println(result);

输出

[CONTACT_QUESTION, ADDRESS_QUESTION]

更好的方法是像这样将映射存储在CODES中:

enum CODES {
    CQ(QUESTIONS.CONTACT_QUESTION),
    AQ(QUESTIONS.ADDRESS_QUESTION),
    WQ(QUESTIONS.WORK_QUESTION);

    private QUESTIONS question;

    CODES(QUESTIONS question) {
        this.question = question;
    }

    public QUESTIONS getQuestion() {
        return question;
    }
}

然后您的代码将变为:

QUESTIONS[] result = Arrays.stream(firstSet_Short)
        .map(CODES::getQuestion)
        .toArray(QUESTIONS[]::new);