Java : 열거 형에 주어진 문자열이 포함되어 있는지 확인하십시오.
여기 내 문제가 있습니다-열거 형에 해당하는 열거 형을 찾고 있습니다 (존재하는 경우) ArrayList.contains();.
내 코드 문제의 샘플은 다음과 같습니다.
enum choices {a1, a2, b1, b2};
if(choices.???(a1)}{
//do this
}
이제는 ArrayList의 Strings가 더 나은 경로 라는 것을 알고 있지만 스위치 / 케이스를 통해 열거 형 내용을 실행해야합니다. 따라서 내 문제.
이와 같은 것이 존재하지 않는다고 가정하면 어떻게 할 수 있습니까?
이것은해야합니다 :
public static boolean contains(String test) {
for (Choice c : Choice.values()) {
if (c.name().equals(test)) {
return true;
}
}
return false;
}
이 방법은 나중에 열거 형 값을 추가하는 것에 대해 걱정할 필요가 없으며 모두 확인됩니다.
편집 : 열거 형이 매우 큰 경우 HashSet에 값을 붙일 수 있습니다.
public static HashSet<String> getEnums() {
HashSet<String> values = new HashSet<String>();
for (Choice c : Choice.values()) {
values.add(c.name());
}
return values;
}
그런 다음 수행 할 수 있습니다 : values.contains("your string")true 또는 false를 반환합니다.
대신 Apache commons lang3 lib를 사용하십시오.
EnumUtils.isValidEnum(MyEnum.class, myValue)
당신이 사용할 수있는 Enum.valueOf()
enum Choices{A1, A2, B1, B2};
public class MainClass {
public static void main(String args[]) {
Choices day;
try {
day = Choices.valueOf("A1");
//yes
} catch (IllegalArgumentException ex) {
//nope
}
}
검사가 자주 실패 할 것으로 예상되는 경우, 다른 루프가 보여준 것처럼 간단한 루프를 사용하는 것이 좋습니다. 열거 형에 많은 값이 포함 된 경우 ( 아마도 HashSet열거 형 또는 이와 유사한 열거 형 값이 문자열로 변환되어 HashSet대신 쿼리 됨) .
Java 1.8을 사용하는 경우 Stream + Lambda를 선택하여이를 구현할 수 있습니다.
public enum Period {
DAILY, WEEKLY
};
//This is recommended
Arrays.stream(Period.values()).anyMatch((t) -> t.name().equals("DAILY1"));
//May throw java.lang.IllegalArgumentException
Arrays.stream(Period.values()).anyMatch(Period.valueOf("DAILY")::equals);
Guavas Enums 는 당신의 친구가 될 수 있습니다
예를 들면 다음과 같습니다.
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;
public static boolean contains(String s)
{
for(choices choice:values())
if (choice.name().equals(s))
return true;
return false;
}
};
먼저 열거 형을 List로 변환 한 다음 list contains 메소드를 사용할 수 있습니다
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
}
여기에 몇 개의 라이브러리가 언급되었지만 실제로 찾고 있던 라이브러리가 그리워졌습니다 : Spring!
거기입니다 ObjectUtils # containsConstant 기본적으로 케이스를 구분하지 않습니다,하지만 당신이 원하는 경우에 엄격한 될 수 있습니다. 다음과 같이 사용됩니다 :
if(ObjectUtils.containsConstant(Choices.values(), "SOME_CHOISE", true)){
// do stuff
}
참고 : 대소 문자를 구분하는 확인을 사용하는 방법을 보여주기 위해 오버로드 된 방법을 사용했습니다. 부울을 생략하여 대소 문자를 구분하지 않는 동작을 수행 할 수 있습니다.
그래도 큰 enum에주의하십시오. 일부처럼 Map 구현을 사용하지 않기 때문에 ...
또한, valueOf의 대소 문자를 구분하지 않는 변형을 제공합니다. ObjectUtils # caseInsensitiveValueOf
이것을 사용할 수 있습니다
YourEnum {A1, A2, B1, B2}
boolean contains(String str){
return Sets.newHashSet(YourEnum.values()).contains(str);
}
솔루션의 효율성을 높이기 위해 @ wightwulf1944에서 제안한 업데이트가 통합되었습니다.
몇 가지 가정 :
1) 예외적 인 흐름 제어이기 때문에 시도 / 캐치가 없습니다.
2) '포함'방법은 일반적으로 여러 번 실행되므로 신속해야합니다.
3) 공간이 제한되지 않습니다 (일반 솔루션의 경우 일반적 임)
import java.util.HashSet;
import java.util.Set;
enum Choices {
a1, a2, b1, b2;
private static Set<String> _values = new HashSet<>();
// O(n) - runs once
static{
for (Choices choice : Choices.values()) {
_values.add(choice.name());
}
}
// O(1) - runs several times
public static boolean contains(String value){
return _values.contains(value);
}
}
나는 생각하지 않지만 다음과 같이 할 수 있습니다.
enum choices {a1, a2, b1, b2};
public static boolean exists(choices choice) {
for(choice aChoice : choices.values()) {
if(aChoice == choice) {
return true;
}
}
return false;
}
편집하다:
Please see Richard's version of this as it is more appropriate as this won't work unless you convert it to use Strings, which Richards does.
Why not combine Pablo's reply with a valueOf()?
public enum Choices
{
a1, a2, b1, b2;
public static boolean contains(String s) {
try {
Choices.valueOf(s);
return true;
} catch (Exception e) {
return false;
}
}
If you're using Apache Commons (or willing to do so), you could check it with:
ArrayUtils.contains(choices.values(), value)
This approach can be used to check any Enum, you can add it to an Utils class:
public static <T extends Enum<T>> boolean enumContains(Class<T> enumerator, String value)
{
for (T c : enumerator.getEnumConstants()) {
if (c.name().equals(value)) {
return true;
}
}
return false;
}
Use it this way:
boolean isContained = Utils.enumContains(choices.class, "value");
This one works for me:
Arrays.asList(YourEnum.values()).toString().contains("valueToCheck");
I created the next class for this validation
public class EnumUtils {
public static boolean isPresent(Enum enumArray[], String name) {
for (Enum element: enumArray ) {
if(element.toString().equals(name))
return true;
}
return false;
}
}
example of usage :
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);
}
You can use valueOf("a1") if you want to look up by String
It is an enum, those are constant values so if its in a switch statement its just doing something like this:
case: val1
case: val2
Also why would you need to know what is declared as a constant?
With guava it's even simpler:
boolean isPartOfMyEnum(String myString){
return Lists.newArrayList(MyEnum.values().toString()).contains(myString);
}
This combines all of the approaches from previous methods and should have equivalent performance. It can be used for any enum, inlines the "Edit" solution from @Richard H, and uses Exceptions for invalid values like @bestsss. The only tradeoff is that the class needs to be specified, but that turns this into a two-liner.
import java.util.EnumSet;
public class HelloWorld {
static enum Choices {a1, a2, b1, b2}
public static <E extends Enum<E>> boolean contains(Class<E> _enumClass, String value) {
try {
return EnumSet.allOf(_enumClass).contains(Enum.valueOf(_enumClass, value));
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
for (String value : new String[] {"a1", "a3", null}) {
System.out.println(contains(Choices.class, value));
}
}
}
com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")
solution to check whether value is present as well get enum value in return :
protected TradeType getEnumType(String tradeType) {
if (tradeType != null) {
if (EnumUtils.isValidEnum(TradeType.class, tradeType)) {
return TradeType.valueOf(tradeType);
}
}
return null;
}
If you are Using Java 8 or above, you can do this :
boolean isPresent(String testString){
return Stream.of(Choices.values()).map(Enum::name).collect(Collectors.toSet()).contains(testString);
}
Set.of(CustomType.values())
.contains(customTypevalue)
public boolean contains(Choices value) {
return EnumSet.allOf(Choices.class).contains(value);
}
enum are pretty powerful in Java. You could easily add a contains method to your enum (as you would add a method to a class):
enum choices {
a1, a2, b1, b2;
public boolean contains(String s)
{
if (s.equals("a1") || s.equals("a2") || s.equals("b1") || s.equals("b2"))
return true;
return false;
}
};
참고URL : https://stackoverflow.com/questions/4936819/java-check-if-enum-contains-a-given-string
'IT' 카테고리의 다른 글
| HttpConfiguration.EnsureInitialized ()를 확인하십시오 (0) | 2020.06.21 |
|---|---|
| Javascript에서 HTML 엔터티를 이스케이프 처리 하시겠습니까? (0) | 2020.06.21 |
| 배열에서 고유 한 값을 얻는 방법 (0) | 2020.06.21 |
| 애니메이션으로 UIView 숨기기 / 보이기 (0) | 2020.06.21 |
| Android Studio에서 작성자 템플릿 변경 (0) | 2020.06.21 |