代码之家  ›  专栏  ›  技术社区  ›  PassionateAbtCoding

删除hashmap[duplicate]的双括号初始化

  •  -2
  • PassionateAbtCoding  · 技术社区  · 3 年前

    我有一个枚举 AuditType

    Map<String, String> (类字段),需要通过迭代 审核类型 常数,并基于if-else条件尝试将这些值放入映射中。

    它已使用复杂的双括号初始化来实现( 我实际上还没有写这个代码

    现在我正试图修复声纳的覆盖范围,因为它抱怨我需要用另一种方式初始化这张地图。

    代码:

    Map<String, String> TYPES = new HashMap<String, String>() {
        {
            Stream.of(AuditType.values()).forEach(auditType -> {
                if (AuditType.ACCOUNT_RECORD.equals(auditType)) {
                    put(AuditCodes.Type.ACCOUNT_ACTIVITY.getCode(), auditType.name());
                } else {
                    String ssCode = AuditCodes.Type.valueOf(auditType.name()).getCode();
                    put(ssCode, auditType.name());
                }
            });
        }
    };
    

    有没有办法不用双括号初始化来编写它?

    2 回复  |  直到 3 年前
        1
  •  1
  •   Alexander Ivanchenko    3 年前

    您可以在枚举常量上创建流并应用 collect() 顺便 toMap() )作为一个论点。

    这种味道 toMap()

    • keyMapper 负责生成 钥匙 ,
    • valueMapper 负责生产的功能
    • mergeFunction -用于解析重复项的函数。

    表示与映射有关的条件逻辑 钥匙 ,可以在 键映射器

    自从 AuditType 是一个 枚举 ,您可以使用身份比较 == 而不是 equals()

    Map<String, String> TYPES = Arrays.stream(AuditType.values())
        .collect(Collectors.toMap(
            auditType -> AuditType.ACCOUNT_RECORD == auditType ? 
                AuditCodes.Type.ACCOUNT_ACTIVITY.getCode() : AuditCodes.Type.valueOf(auditType.name()).getCode(),
            AuditType::name,
            (v1, v2) -> v2 // map the duplicated key to the latest value
        ));
    
        2
  •  1
  •   erickson    3 年前

    private static final Map<String, String> auditTypeByCode = auditTypeByCodeMap();
    
    private static Map<String, String> auditTypeByCodeMap() {
      Map<String, String> index = new HashMap<String, String>();
      for (AuditType auditType : AuditType.values()) {
        String val = auditType.name();
        AuditCodes.Type key = (auditType == AuditType.ACCOUNT_RECORD)
          ? AuditCodes.Type.ACCOUNT_ACTIVITY
          : AuditCodes.Type.valueOf(val);
        index.put(key.getCode(), val);
      }
      return index;
    }