Bic*_*ick 7 java enums java-8 java-stream
我有一个enum
与另一个enum
作为参数
public enum MyEntity{
Entity1(EntityType.type1,
....
MyEntity(EntityType type){
this.entityType = entityType;
}
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个返回enum
按类型的方法
public MyEntity getEntityTypeInfo(EntityType entityType) {
return lookup.get(entityType);
}
Run Code Online (Sandbox Code Playgroud)
通常我会写
private static final Map<EntityType, EntityTypeInfo> lookup = new HashMap<>();
static {
for (MyEntity d : MyEntity.values()){
lookup.put(d.getEntityType(), d);
}
}
Run Code Online (Sandbox Code Playgroud)
用java流编写它的最佳实践是什么?
Ale*_* C. 15
我猜你的代码中有一些拼写错误(我认为该方法应该是静态的,你的构造函数目前正在进行无操作),但如果我关注你,你可以从枚举数组中创建一个流并使用toMap
收集器,将每个枚举与其EntityType
键映射,并将实例本身映射为值:
private static final Map<EntityType, EntityTypeInfo> lookup =
Arrays.stream(EntityTypeInfo.values())
.collect(Collectors.toMap(EntityTypeInfo::getEntityType, e -> e));
Run Code Online (Sandbox Code Playgroud)
该toMap
回收不做出关于地图实现任何保证返回(尽管它目前是HashMap
),但你总是可以使用重载的变种,如果你需要更多的控制,提供了一个投掷合并为参数.
您还可以使用静态类的另一个技巧,并在构造函数中填充地图.
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 ) );
}
Run Code Online (Sandbox Code Playgroud)