【问题标题】:How to store enum to map using Java 8 stream API如何使用 Java 8 流 API 将枚举存储为映射
【发布时间】:2015-06-29 10:10:54
【问题描述】:

我有一个enum 和另一个enum 作为参数

public enum MyEntity{
   Entity1(EntityType.type1,
    ....


   MyEntity(EntityType type){
     this.entityType = entityType;
   }
}

我想创建一个按类型返回enum 的方法

public MyEntity getEntityTypeInfo(EntityType entityType) {
        return lookup.get(entityType);
    }

通常我会写

private static final Map<EntityType, EntityTypeInfo> lookup = new HashMap<>();

static {
    for (MyEntity d : MyEntity.values()){
        lookup.put(d.getEntityType(), d);
    }
}

用 java 流编写它的最佳实践是什么?

【问题讨论】:

  • 你的枚举是EntityTypeInfo还是MyEntity

标签: java enums java-8 java-stream


【解决方案1】:

我猜您的代码中有一些拼写错误(我认为该方法应该是静态的,您的构造函数目前正在执行空操作),但是如果我在关注您,您可以从枚举数组并使用toMap 收集器,将每个枚举与其EntityType 映射为键,并将实例本身映射为值:

private static final Map<EntityType, EntityTypeInfo> lookup =
    Arrays.stream(EntityTypeInfo.values())
          .collect(Collectors.toMap(EntityTypeInfo::getEntityType, e -> e));

toMap 收集器不保证返回的 map 实现(尽管它目前是 HashMap),但如果您需要更多控制,您可以随时使用 overloaded 变体,提供一个抛出合并作为参数.

您也可以使用another trick with a static class,并在构造函数中填充地图。

【讨论】:

  • 您可以使用Function.identity() 而不是e -&gt; e 来改进这一点,因为Function.identity() 总是返回相同的函数。
  • @dustin.schultz e -&gt; e 完全一样,因为这个 lambda 表达式不捕获值,它将是一个在每次调用时重复使用的单例。此外,Function.identity() 实现为return t -&gt; t;
  • 啊,是的,不捕获,所以使用单例。我仍然认为 Function.identity() 非常清楚。 :)
  • @dustin.schultz 品味问题,我猜。我发现e -&gt; e 非常明确且简短,但每个人都有自己的偏好;-)。
  • Stream.of()Arrays.stream() 好:)
【解决方案2】:
public enum FibreSpeed {
        a30M( "30Mb Fibre Connection - Broadband Only", 100 ),
        a150M( "150Mb Fibre Connection - Broadband Only", 300 ),
        a1G( "1Gb Fibre Connection - Broadband Only", 500 ),
        b30M( "30Mb Fibre Connection - Broadband & Phone", 700 ),
        b150M( "150Mb Fibre Connection - Broadband & Phone", 900 ),
        b1G( "1Gb Fibre Connection - Broadband & Phone", 1000 );

        public String speed;
        public int    weight;

        FibreSpeed(String speed, int weight) {
            this.speed = speed;
            this.weight = weight;
        }

        public static Map<String, Integer> SPEEDS = Stream.of( values() ).collect( Collectors.toMap( k -> k.speed, v -> v.weight ) );
    }

【讨论】:

    猜你喜欢
    • 2018-04-11
    • 2019-10-09
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 2019-07-06
    • 1970-01-01
    相关资源
    最近更新 更多