Reputation: 13
I have a basic if-else if block of code. Here is the simplified version
if (var == 1) {
finalString = "string1";
} else if (var == 3) {
finalString = "string3";
} else if (var == 4) {
finalString = "string4";
} else {
finalString = "no string found";
}
I am trying to use enums approach, so I created an enum class
public enum MyValues {
string1(1),
string2(3),
string4(4);
...
...
}
Is there a way to improve my if/else statements with the enum I created?
Upvotes: 1
Views: 61
Reputation: 1524
If you really HAVE TO use enums, you can do something like this:
public enum MyValues {
string1(1),
string2(3),
string4(4),
default_value(-1);
private final int key;
MyValues(int key) {
this.key = key;
}
public MyValues getByKey(int key){
return Arrays.stream(values())
.filter(e -> e.key == key)
.findAny()
.orElse(default_value);
}
}
If you don't have to use enums, then see azro's answer.
Upvotes: 2
Reputation: 54168
You'd better use a Map
for mapping int <--> String
Map<Integer, String> map = Map.of(1, "string1", 2, "string2", 3, "string3");
int aKey = 1;
String finalString = map.getOrDefault(aKey, "no string found");
System.out.println(map.getOrDefault( 1, "no string found")); // string1
System.out.println(map.getOrDefault(10, "no string found")); // no string found
Upvotes: 6