我有以下枚举,但我只想迭代第二个参数,而不必迭代此类别之外的枚举成员,所以如果我有一个消息
:“消息"和类别 "Category"
我也可以在方法 isMessageInGroup
中将类别指定为参数,而不必迭代那些具有其他类别的类别,例如 MESSAGE_3
:"另一个类别"
有没有一种巧妙的方法可以做到这一点并节省一些迭代时间?即使有很多值(value),这也可能不会显着影响性能,但我想知道这是否可能。搜索了一下,但很难找到这个具体问题。
下面的枚举确实按类别对消息收费,但我想知道我是否可以避免迭代想要的类别之外的消息
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;
}
}
最佳答案
正如评论所说,开箱即用的枚举对此不是最有效的,因为您将不得不使用迭代器。但是,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);
}
}
编辑:如果您选择实现类似messagesInGroup
的方法,最安全的方法是使用不可修改的Set
实现它,以便保护枚举内部的完整性。
public static Set<String> messagesInGroup(String category) {
return Collections.unmodifiableSet(
map.getOrDefault(category, Collections.emptySet())
);
}
关于java - 按参数迭代枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37932468/