enum MyData {
ONE,
TWO
}
@Test
public void test() {
if (!Enums.getIfPresent(MyData.class, "THREE").isPresent()) {
System.out.println("THREE is not here");
}
}
enum Choices{A1, A2, B1, B2};
List choices = Arrays.asList(Choices.values());
//compare with enum value
if(choices.contains(Choices.A1)){
//do something
}
//compare with String value
if(choices.contains(Choices.valueOf("A1"))){
//do something
}
public class EnumUtils {
public static boolean isPresent(Enum enumArray[], String name) {
for (Enum element: enumArray ) {
if(element.toString().equals(name))
return true;
}
return false;
}
}
用法示例:
public ArrivalEnum findArrivalEnum(String name) {
if (!EnumUtils.isPresent(ArrivalEnum.values(), name))
throw new EnumConstantNotPresentException(ArrivalEnum.class,"Arrival value must be 'FROM_AIRPORT' or 'TO_AIRPORT' ");
return ArrivalEnum.valueOf(name);
}
// Build the set.
final Set<String> mySet = Arrays//
.stream(YourEnumHere.values())//
.map(Enum::name)//
.collect(Collectors.toSet());
// Reuse the set for contains multiple times.
mySet.contains(textA);
mySet.contains(textB);
...