通过传递2个参数进行枚举查找



如何通过传递水果和蔬菜参数来获得枚举。

public enum EnumType {
A("Apple", "Asparagus"),
B("Banana", "Brocolli"),
C("Candy", "Carrot");
public final String fruit;
public final String vegetable;
EnumType(String fruit, String vegetable) {
this.fruit= fruit;
this.vegetable= vegetable;
}
....
}

这必须通过迭代并比较fruitvegetable成员来实现。所以类似于:

EnumType find(String fruit, String vegetable) {
for (EnumType t : EnumType.values()) {

if(t.fruit.equals(fruit) && t.vegetable.equals(vegetable)) {
return t;
}
}
return null;
}

如果你的枚举是按字母顺序排列的,你可以使用fruit.charAt(0(.toUpperCase((来引用它,以获得水果的第一个字母。然后(我认为(您可以使用valueOf((来引用与该字母对应的行。如果我错了,请纠正我——我对enums还比较陌生。

public static EnumType ofFruit(String fruit) {
for (EnumType e : values()) {}
if (e.fruit.equals(fruit)) {
return e;
}
}
return null;
// or throw new IllegalArgumentException("No such enum constant");
}

public static EnumType ofVegetable(String vegetable) {
for (EnumType e : values()) {}
if (e.vegetable.equals(vegetable)) {
return e;
}
}
return null;
// or throw new IllegalArgumentException("No such enum constant");
}
public static EnumType ofFruitAndVegetable(String fruit, String vegetable) {
for (EnumType e : values()) {
if (e.fruit.equals(fruit) && e.vegetable.equals(vegetable)) {
return e;
}
}
return null;
// or throw new IllegalArgumentException("No such enum constant");
}

这取决于你到底需要什么。

如果您有其他枚举,可以方便地添加一个通用搜索方法,所有枚举类都可以调用该方法来匹配任何类型的字段:

public static <T,V> T find(T[] values, V fieldValue, Function<T,V> ... lookupValueFunc) {
for (var func : lookupValueFunc)
for (T item : values)
if(Objects.equals(func.apply(item), fieldValue))
return item;
return null;
}

然后,每个枚举都可以用lambda声明自己的find(),如下所示,以选择一种类型的输入的特定字段——在EnumType:的情况下为String

public static EnumType findByName(String name) {
return find(EnumType.values(), name, e -> e.fruit,  e -> e.vegetable);
}
public static void main(String[] args)
{
for (var x : new String[] {"Apple", "Asparagus", "Banana", "Brocolli", "Carrot", "Candy"})
System.out.println(x+" => "+EnumType.findByName(x));
}
Apple => A
Asparagus => A
Banana => B
Brocolli => B
Carrot => C
Candy => C

最新更新