With an enum like this one where each key has several values
ABBR1("long text 1", "another description 1", "yet another one 1"),
ABBR2("long text 2", "another description 2", "yet another one 2"),
//and so on...
how can I reverse lookup an abbreviation (constant) by calling a method like getAbbreviation(descriptionText)
?
I'm basically looking for an implementation as described here, I think, but with the difference that each ENUM key (constant) has several values coming with it, and I want it to work with getAbbreviation("long text 1")
as well as with getAbbreviation("yet another one 2")
...
Is there an easy way to loop over each ENUM's (i.e. ABBRn
's) value fields, to populate a giant map, or is there maybe even a better solution?
This relies on the fact that the enum member constructors are run before the static initializer. The initializer then caches the members and their long forms.
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public enum Abbreviation {
ABBR1("long text 1", "another description 1", "yet another one 1"),
ABBR2("long text 2", "another description 2", "yet another one 2");
private static final Map<String, Abbreviation> ABBREVIATIONS = new HashMap<>();
private String[] longForms;
private Abbreviation(String... longForms) {
this.longForms = longForms;
}
public String toString () {
return Arrays.toString(longForms);
}
static {
for(Abbreviation abbr : values()) {
for(String longForm : abbr.longForms) {
ABBREVIATIONS.put(longForm, abbr);
}
}
}
public static Abbreviation of(String longForm) {
Abbreviation abbreviation = ABBREVIATIONS.get(longForm);
if(abbreviation == null) throw new IllegalArgumentException(longForm + " cannot be abbreviated");
return abbreviation;
}
public static void main(String[] args) {
Abbreviation a = Abbreviation.of("yet another one 2");
System.out.println(a == Abbreviation.ABBR2); //true
}
}