假设我有一个包含100个值的枚举.为简单起见,请参考以下示例:
public enum code
{
CODE_1("string1"),
CODE_2("string2"),
CODE_3("string3"),
CODE_4("string4"),
...
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个公共方法与已知的格式字符串(如"字符串1","字符串2" ......)转换中选取适当的枚举值CODE_1,CODE_2 ......这通常是通过遍历所有的值来实现的,如果找到匹配项,返回该枚举值.(详情可在此问题中找到.)
但是,我关注的是对所有值进行reguraly循环.这可能是一个巨大的瓶颈吗?如果不是100个元素,那么有1000个?
作为我自己的练习,我尝试使用静态地图优化此查找,这可以确保给定任何字符串的O(1)查找时间.我喜欢这个额外的噱头,但我只想在我的代码中包含它,如果它确实是必要的.使用迭代方法和map方法有什么想法和发现?
public enum Code
{
...
//enum values
...
//The string-to-Code map
private static final Map<String,Code> CODE_MAP = populateMap();
private static Map<String,Code> populateMap()
{
Map<String,Code> map = new HashMap<String,Code>();
for(Code c : Code.values())
{
map.put(c.getCode(), c);
}
return map;
}
private String code;
private Code(String code)
{
this.code = code;
}
public String getCode()
{
return this.code;
}
public Code convertFromString(String code)
{ …Run Code Online (Sandbox Code Playgroud) 我有一个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流编写它的最佳实践是什么?
我想根据条件返回流的值。仅以以下为例,我想将任何苹果映射到Food.APPLE:
public enum Food {
APPLE, APPLE2, APPLE3, BANANA, PINEAPPLE, CUCUMBER;
private static final Food[] APPLES = new Food[] {APPLE, APPLE2, APPLE3};
//java7
public Food fromValue(String value) {
for (Food type : Food.values()) {
if (type.name().equalsIgnoreCase(value)) {
return ArrayUtils.contains(APPLES, type) ? APPLE : type;
}
}
return null;
}
//java8: how to include the array check for APPLES?
public Food fromValue(String value) {
return Arrays.stream(Food.values()).
filter(type -> type.name().equalsIgnoreCase(value))
.findFirst()
.orElse(null);
}
}
Run Code Online (Sandbox Code Playgroud)
如何在流中包含三元条件?