按名称映射枚举值

Mapping enum values by its name

我试图通过它的组件类型来映射这个枚举的所有值。不幸的是我不知道如何将它映射到数组,尝试使用 toImmutableMap (v-> v.componentType, v-> v) 但这只适用于 ImmutableMap<String, MatchType> 并且我需要将它映射为数组(MatchType[]),有人可以告诉我如何我可以做到或者有更好的方法吗?

ImmutableMap<String, MatchType[]> findByComponentType = Arrays.stream(MatchType.values()).collect(toImmutableMap(v -> /** what to put here */));

示例:如果我使用 findByComponentType.get("android.support.v4.app.Fragment") 它应该 return SUPPORT_FRAGMENT & SUPPORT_FRAGMENT_PRE_API23.

 private enum MatchType {
  ACTIVITY(
      "android.app.Activity",
      "onCreate",
  FRAMEWORK_FRAGMENT(
      "android.app.Fragment",
      "onAttach",
  FRAMEWORK_FRAGMENT_PRE_API23(
      "android.app.Fragment",
      "onAttach",,
  SUPPORT_FRAGMENT(
      "android.support.v4.app.Fragment",
      "onAttach",
  SUPPORT_FRAGMENT_PRE_API23(
      "android.support.v4.app.Fragment",
      "onAttach");

  MatchType(String componentType, String lifecycleMethod) 

而不是 ImmutableMap<String, MatchType[]> 你真的想要 ImmutableMultimapImmutableSetMultimap 特别是因为你的值将是适合 set 而不是 array/list 的枚举值)。

像这样创建反向映射:

private static final ImmutableSetMultimap<String, MatchType> COMPONENT_TYPE_LOOKUP =
        EnumSet.allOf(MatchType.class).stream()
                .collect(toImmutableSetMultimap(
                        matchType -> matchType.componentType, // or MatchType::getComponentType if there's a getter,
                        matchType -> matchType                // or Function.identity()
                ));

然后你会

static Set<MatchType> findByComponentType(String componentType) {
    return COMPONENT_TYPE_LOOKUP.get(componentType);
}

最后它会 return 一组匹配类型:

@Test
public void shouldMatchType() {
    final Set<MatchType> types = findByComponentType("android.support.v4.app.Fragment");
    assertThat(types)
            .containsExactlyInAnyOrder(MatchType.SUPPORT_FRAGMENT,
                                       MatchType.SUPPORT_FRAGMENT_PRE_API23);