枚举的几种写法


1.这种用到了stream,有点秀操作的感觉

Function.identity()的使用详解

@AllArgsConstructor
@Getter
public enum MessageTypeEnum {
    TEXT(1, "正常"),
    RECALL(2, "撤回消息"),
    ;

    private final Integer type;
    private final String desc;

    private static Map<Integer, MessageTypeEnum> cache;

    static {
        cache = Arrays.stream(MessageTypeEnum.values()).collect(Collectors.toMap(MessageTypeEnum::getType, Function.identity()));
    }

    public static MessageTypeEnum of(Integer type) {
        return cache.get(type);
    }
}

2.普通写法

@Getter
@AllArgsConstructor
public enum SearchModeEnum {
    /**
     * mysql
     */
    MYSQL("mysql", "mySqlSearchStrategyImpl"),
    /**
     * elasticsearch
     */
    ELASTICSEARCH("elasticsearch", "esSearchStrategyImpl");

    /**
     * 模式
     */
    private final String mode;

    /**
     * 策略
     */
    private final String strategy;

    /**
     * 获取策略
     *
     * @param mode 模式
     * @return {@link String} 搜索策略
     */
    public static String getStrategy(String mode) {
        for (SearchModeEnum value : SearchModeEnum.values()) {
            if (value.getMode().equals(mode)) {
                return value.getStrategy();
            }
        }
        return null;
    }

}

3.chatgpt优化的写法

使用静态代码块替代流操作初始化缓存:虽然使用流操作和Collectors.toMap()方法可以方便地初始化缓存,但在这个特定的情况下,使用静态代码块可能更简洁和高效。静态代码块在类加载时执行,并且只会执行一次。因此,可以将初始化缓存的逻辑放入静态代码块中,而无需在每次调用of()方法时重新计算缓存。以下是优化后的代码示例:

@AllArgsConstructor
@Getter
public enum MessageTypeEnum {
    TEXT(1, "正常"),
    RECALL(2, "撤回消息"),
    ;

    private final Integer type;
    private final String desc;

    private static final Map<Integer, MessageTypeEnum> cache;

    static {
        cache = new HashMap<>();
        for (MessageTypeEnum messageType : MessageTypeEnum.values()) {
            cache.put(messageType.getType(), messageType);
        }
    }

    public static MessageTypeEnum of(Integer type) {
        return cache.get(type);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值