Reputation: 101
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}
Upvotes: 2
Views: 1444
Reputation: 7917
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);
Upvotes: 1