0

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?

1
  • 1
    You’re better off with a nested loop. Commented Aug 30, 2021 at 15:40

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.