反向查找每个键/常量具有多个值的Java枚举?

时间:2014-10-13 10:51:17

标签: java enums lookup reverse-lookup

使用类似这样的枚举,其中每个键都有多个值

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...

如何通过调用像getAbbreviation(descriptionText)

这样的方法来反转查找缩写(常量)

我基本上都在寻找here所描述的实现,但不同之处在于每个ENUM键(常量)都有几个值,我希望它与{{1}一起使用和} getAbbreviation("long text 1") ...

是否有一种简单的方法可以遍历每个ENUM(即getAbbreviation("yet another one 2"))的值字段,填充巨型地图,还是可能有更好的解决方案?

3 个答案:

答案 0 :(得分:2)

每个枚举都有一个方法值(),所以你可以这样做:

for(YourEnum type : values()){
        if(/*is Equal to Your descriptionText*/){
             return type;
        }
    }
    throw new IllegalArgumentException("No such BailiffPaymentStatus:"+dbRepresentation);

答案 1 :(得分:2)

这依赖于枚举成员构造函数在静态初始化程序之前运行的事实。初始化程序然后缓存成员及其长形式。

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

答案 2 :(得分:1)

我认为来自:c.P.u1的解决方案是正确的。但是,在使用此问题的解决方案时,有一种更直接的方法来填充HashMap。

  • How to facilitate Netbeans Designer to load JPanel-s that use an enum reverse-lookup using hashmap?

        private static final Map<String, Abbreviation> abbreviationMap;
    
        private Abbreviation(String... longForms) {
            this.longForms = longForms;   //  optional
            mapAbbreviations( this, longForms )
        }
    
        private static void mapAbbreviations( final Status state, String... longForms ){
            if( null ==  abbreviationMap  ){
                abbreviationMap  = new HashMap( 20 );
            }
            for( String abbrev : longForms ){
                abbreviationMap.put( abbrev,  state );
            }
        }
    

此外,对于toString()函数,您并不需要私有的longForms字符串数组,因为所有的值都会与Map一起保存。