英文:
How to get enum value from string if value doesn't match
问题
我有枚举:
public enum Enumz{
FIRST_VALUE(0, "one"),
SECOND_VALUE(1, "two"),
THIRD_VALUE(2, "three")
private int id;
private String name;
}
如果我的字符串值与枚举字符串名称匹配,我该如何找到枚举值?例如:如果我有 String = "two"
,我需要获得 ENUMZ.SECOND_VALUE
。
英文:
I have enum:
public enum Enumz{
FIRST_VALUE(0, "one"),
SECOND_VALUE(1, "two"),
THIRD_VALUE(2, "three")
private int id;
private String name;
}
How can I find enum value if my String value match with enum string name? For example: if I have String = "two"
I need to get ENUMZ.SECOND_VALUE
.
答案1
得分: 1
public enum Enumz {
FIRST_VALUE(0, "one"),
SECOND_VALUE(1, "two"),
THIRD_VALUE(2, "three");
private int id;
private String name;
Enumz(int id, String name) {
this.id = id;
this.name = name;
}
public static Enumz fromString(String text) {
for (Enumz b : Enumz.values()) {
if (b.name.equalsIgnoreCase(text)) {
return b;
}
}
return null;
}
}
class Sample {
public static void main(String[] args) {
System.out.println(Enumz.fromString("two"));
}
}
OUTPUT
SECOND_VALUE
英文:
public enum Enumz {
FIRST_VALUE(0, "one"),
SECOND_VALUE(1, "two"),
THIRD_VALUE(2, "three");
private int id;
private String name;
Enumz(int id, String name) {
this.id = id;
this.name = name;
}
public static Enumz fromString(String text) {
for (Enumz b : Enumz.values()) {
if (b.name.equalsIgnoreCase(text)) {
return b;
}
}
return null;
}
}
class Sample{
public static void main(String[] args) {
System.out.println(Enumz.fromString("two"));
}
}
You can implement your own method inside enum and call that method every time you want enum using String.
Above code will printing an output as below
OUTPUT
SECOND_VALUE
答案2
得分: 1
你可以使用Java 8的stream
替代for循环
。
String serachValue = "two";
Enumz enumz = Arrays.stream(Enumz.values())
.filter(v -> serachValue.equalsIgnoreCase(v.name))
.findFirst().orElse(null);
良好的做法是将它作为静态方法放入ENUM
本身,正如其他人@Sagar Gangwal所解释的那样。
英文:
You can use Java 8 stream
alternative to for loop
String serachValue = "two";
Enumz enumz = Arrays.stream(Enumz.values())
.filter(v -> serachValue.equalsIgnoreCase(v.name))
.findFirst().orElse(null);
Good practice is always put it as a static method into the ENUM
itself as explained by other @Sagar Gangwal.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论