Reputation: 4613
Cannot understand how to compose Map<InternalErrorCode, ExternalErrorCode>
variable from the following enum structure using Stream API:
@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;
}
Can someone assist with it?
Upvotes: 0
Views: 145
Reputation: 15136
The declaration of the lookup LOOKUP_BY_ERROR_CODE
can use a Stream with flatMap
which expands all combinations of known InternalErrorCode
to ExternalErrorCode
mappings. There is no need to check for empty sets as these will just be mapped as an empty stream, and finally the collector assembles the entries as a 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}
The above code will detect if there is duplicate mappings from internal to external - this gets reported by Collectors.toMap
as:
java.lang.ExceptionInInitializerError
Caused by: java.lang.IllegalStateException Duplicate key XXX
Upvotes: 1