【问题标题】:Convert enum array with set of nested enums to Map将具有嵌套枚举集的枚举数组转换为 Map
【发布时间】:2021-08-30 11:47:32
【问题描述】:

无法理解如何使用 Stream API 从以下枚举结构中组合 Map<InternalErrorCode, ExternalErrorCode> 变量:

@Getter
@RequiredArgsConstructor
public enum ExternalErrorCode {

    // Internal error codes won't be duplicated across any ExternalErrorCode enums
    ERROR1(Set.of(InternalErrorCode.FOO, InternalErrorCode.BAR)),
    ERROR2(Set.of(InternalErrorCode.ZOO)),
    ...;

    // Expected output should be: [{"FOO","ERROR1"}, {"BAR","ERROR1"}, {"ZOO","ERROR2"}]
    private static final Map<InternalErrorCode, ExternalErrorCode> LOOKUP_BY_ERROR_CODE = Stream.of(ExternalErrorCode.values())
                                                                                           .filter(not(externalErrorCode -> externalErrorCode.getErrorCode().isEmpty()))
                                                                                           .collect(groupingBy(...)); // Here is unclarity

    private final        Set<InternalErrorCode>                            errorCode;

}

有人可以帮忙吗?

【问题讨论】:

  • 最好使用嵌套循环。

标签: java java-stream


【解决方案1】:

查找LOOKUP_BY_ERROR_CODE 的声明可以使用带有flatMap 的Stream,它将已知InternalErrorCode 的所有组合扩展为ExternalErrorCode 映射。无需检查空集,因为它们只会被映射为空流,最后收集器将条目组装为 Map:

private static final Map<InternalErrorCode, ExternalErrorCode> LOOKUP_BY_ERROR_CODE
    = Stream.of(ExternalErrorCode.values())
            .flatMap(e -> e.errorCode.stream().map(i -> Map.entry(i, e)))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

=>

LOOKUP_BY_ERROR_CODE={ZOO=ERROR2, BAR=ERROR1, FOO=ERROR1}

以上代码将检测是否存在从内部到外部的重复映射 - 这由Collectors.toMap 报告为:

java.lang.ExceptionInInitializerError 
Caused by: java.lang.IllegalStateException Duplicate key XXX

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多