2

Using Java 8 Streams how to convert an Array of Enum Objects to an other Enum Object Array

Class Structure

 enum QUESTIONS {
        CONTACT_QUESTION,
        ADDRESS_QUESTION,
        WORK_QUESTION
    };

 enum CODES {
       CQ,
       AQ,
       WQ
    };

INPUT

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

OUTPUT

QUESTIONS[] firstSet_Long = {QUESTIONS.CONTACT_QUESTION, QUESTIONS.ADDRESS_QUESTION}
3
  • What's the background/context for that mapping ? Seems there's a better solution in surrounding design than solving by streaming. Commented Feb 14, 2019 at 21:59
  • context is api-of-backend returns a enum of codes(shorter ones) while the frontend need an enum of questions(longer version) Commented Feb 14, 2019 at 22:09
  • Possibly related/dupe stackoverflow.com/questions/32709686/two-related-enums-mapping Commented Feb 15, 2019 at 2:48

1 Answer 1

1

Here I am matching the initials of the codes like 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);

Output

[CONTACT_QUESTION, ADDRESS_QUESTION]

A better way would be to store a mapping in CODES like this:

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

And then your code will become:

QUESTIONS[] result = Arrays.stream(firstSet_Short)
        .map(CODES::getQuestion)
        .toArray(QUESTIONS[]::new);
Sign up to request clarification or add additional context in comments.

1 Comment

The solution suggested latter, should be the way one could say, since the server as mentioned by OP could then be sending AMAZNING_QUESTION and clients can still represent it as AQ. But maybe they might be looking for a reversed mapping in my opinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.