반응형
Java 8에서 문자열 목록으로 열거 값 가져오기
다음과 같이 Enum 값을 문자열 목록으로 반환하는 Java 8 메서드 또는 쉬운 방법이 있습니까?
List<String> sEnum = getEnumValuesAsString();
다음 작업을 수행할 수 있습니다(Java 8 이전).
List<Enum> enumValues = Arrays.asList(Enum.values());
또는
List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));
Java 8 기능을 사용하면 각 상수를 이름에 매핑할 수 있습니다.
List<String> enumNames = Stream.of(Enum.values())
.map(Enum::name)
.collect(Collectors.toList());
다음과 같은 작업을 수행할 수도 있습니다.
public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())
또는
EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())
이 질문을 우연히 접하게 된 주된 이유는 특정 문자열 열거 이름이 특정 열거 유형에 대해 유효한지 여부를 검증하는 범용 검증기를 쓰고 싶었기 때문입니다(누군가 유용하다고 생각하는 경우 공유).
검증을 위해서, 나는 그 증명서를Apache's EnumUtils
컴파일 시 Enum 유형을 알 수 없기 때문에 라이브러리입니다.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
Set<String> notAllowedNames = enumNames.stream()
.filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
.collect(Collectors.toSet());
if (notAllowedNames.size() > 0) {
String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
.collect(Collectors.joining(", "));
throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
.collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
+ "of the following : " + validEnumNames);
}
}
여기 https://stackoverflow.com/a/51109419/1225551에 나와 있는 것처럼 열거형 주석 검증기를 쓰는 것이 너무 귀찮았습니다.
언급URL : https://stackoverflow.com/questions/29465943/get-enum-values-as-list-of-string-in-java-8
반응형
'programing' 카테고리의 다른 글
자동 증가가 mysql에서 생성할 수 있는 가장 큰 ID 번호는 무엇입니까? (0) | 2023.01.12 |
---|---|
pytest에서 콘솔에 인쇄하는 방법 (0) | 2023.01.12 |
MariaDB 10에서 대용량 인덱스를 활성화하려면 어떻게 해야 합니까? (0) | 2023.01.12 |
어레이에 개체를 추가하는 방법 (0) | 2023.01.12 |
JavaScript 약속 - 거부 vs. throw (0) | 2023.01.12 |