【问题标题】:Mapping enum values by its name按名称映射枚举值
【发布时间】:2021-08-18 22:05:10
【问题描述】:

我正在尝试通过它的componentType来映射这个枚举的所有值。不幸的是,我不知道如何将它与数组映射,尝试使用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"),它应该返回 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) 

【问题讨论】:

  • 你需要groupingBy
  • @BoristheSpider 感谢它的工作

标签: java guava


【解决方案1】:

您真正想要的是ImmutableMultimap,而不是ImmutableMap<String, MatchType[]>ImmutableSetMultimap,因为您的值将是适合设置而不是数组/列表的枚举值)。

像这样创建你的反向映射:

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);
}

最后它会返回一组匹配的类型:

@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);

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 2023-03-23
    • 1970-01-01
    • 2017-10-21
    相关资源
    最近更新 更多