通过参数迭代枚举

rin*_*ngo 1 java enums

我有以下枚举,但我想迭代第二个参数而不必迭代这个类别之外的枚举成员,所以如果我有一个message:"消息"和类别"Category"我可以指定类别作为参数在方法中,isMessageInGroup无需迭代那些与另一类别,如MESSAGE_3:"另一类别"

有没有一种巧妙的方法来节省一些迭代时间?可能甚至没有大量的价值,这将显着影响性能,但我想知道是否可能.搜索了一下但很难找到这个具体问题.

下面的枚举确实按类别对消息收费但我想知道我是否可以避免迭代那些想要的类别之外的消息

public enum MessagesEnum {
    MESSAGE_1("Message", "Category"),
    MESSAGE_2("Another Message", "Category"),
    MESSAGE_3("Odd Message", "Another Category");

    private final String message;
    private final String category;

    SabreErrorMessages(String message, String errorCategory) {
        this.message = message;
        this.category = category;
    }

    public String getMessage() {
        return message;
    }

    public String getCategory() {
        return category;
    }

    public static boolean isMessageInGroup(String message){
        for(MessagesEnum message : MessagesEnum.values()) {
            if(message.contains(message.getMessage()) && message.getCategory().equals("Category")) {
                return true;
            }
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

4ca*_*tle 5

正如评论所说,开箱即用的枚举对此不会是最有效的,因为你将不得不使用迭代器.HashMap但是,平均提供O(1)查找并且速度会快得多.

public enum Messages {

    MESSAGE_1("Message", "Category"),
    MESSAGE_2("Another Message", "Category"),
    MESSAGE_3("Odd Message", "Another Category");

    private static final Map<String, Set<String>> map = new HashMap<>();
    static {
        for (Messages m : Messages.values()) {
            map.computeIfAbsent(m.category, s -> new HashSet<>()).add(m.message);
        }
    }

    private final String message, category;

    private Messages(String message, String category) {
        this.message = message;
        this.category = category;
    }

    public String getMessage() { return message; }
    public String getCategory() { return category; }

    public static boolean isMessageInGroup(String message){
        // use `getOrDefault` if `get` could return null!!
        return map.get("Category").contains(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ideone演示

编辑:如果您选择实现类似的方法messagesInGroup,最安全的方法是使用不可修改的方法来实现它Set,以保护枚举内部的完整性.

public static Set<String> messagesInGroup(String category) {
    return Collections.unmodifiableSet(
        map.getOrDefault(category, Collections.emptySet())
    );
}
Run Code Online (Sandbox Code Playgroud)

  • 而已.虽然我怀疑OP实际上想要一个`isMessageInGroup`方法,但这只是他尝试解决方案.可能更有用的方法是`Collection <Message> MessagesInGroup(string category){return map.get(category); }`允许应用程序代码执行它所需的操作. (2认同)