如何使用 Java 8 流 API 存储枚举以进行映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31112967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store enum to map using Java 8 stream API
提问by Bick
I have an enum
with another enum
as a parameter
我有一个enum
与另一个enum
作为参数
public enum MyEntity{
Entity1(EntityType.type1,
....
MyEntity(EntityType type){
this.entityType = entityType;
}
}
I want to create a method that return the enum
by type
我想创建一个返回enum
by 类型的方法
public MyEntity getEntityTypeInfo(EntityType entityType) {
return lookup.get(entityType);
}
usually I would have written
通常我会写
private static final Map<EntityType, EntityTypeInfo> lookup = new HashMap<>();
static {
for (MyEntity d : MyEntity.values()){
lookup.put(d.getEntityType(), d);
}
}
What is the best practice to write it with java stream?
用java流编写它的最佳实践是什么?
回答by Alexis C.
I guess there are some typos in your code (the method should be static in my opinion, your constructor is doing a no-op at the moment), but if I'm following you, you can create a stream from the array of enums and use the toMap
collector, mapping each enum with its EntityType
for the keys, and mapping the instance itself as a value:
我猜您的代码中有一些拼写错误(我认为该方法应该是静态的,您的构造函数目前正在执行无操作),但是如果我关注您,您可以从枚举数组中创建一个流并使用toMap
收集器,将每个枚举与其EntityType
键映射,并将实例本身映射为值:
private static final Map<EntityType, EntityTypeInfo> lookup =
Arrays.stream(EntityTypeInfo.values())
.collect(Collectors.toMap(EntityTypeInfo::getEntityType, e -> e));
The toMap
collector does not make any guarantee about the map implementation returned (although it's currently a HashMap
), but you can always use the overloadedvariant if you need more control, providing a throwing merger as parameter.
该toMap
回收不作出关于返回的映射实现任何保证(尽管它目前是HashMap
),但你总是可以使用重载的变种,如果你需要更多的控制,提供了一个投掷合并为参数。
You could also use another trick with a static class, and fill the map in the constructor.
回答by dobrivoje
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 ) );
}