I wonder if there is a more elegant way to write an if statement with a lot of || in java. I've given different values to alphabet letters:
A,O,I,B,T,S,M,N -> 1
C,D,F,G -> 5
W,Y,Z,H,Q -> 10
So, I want to check a given letter and if is equal with one of the 2nd group for example to get 5. Right now I'm checking like this:
String value;
if (getLetter().equals("Α")|| getLetter().equals("O") ||
getLetter().equals("I") || getLetter().equals("B") ||
getLetter().equals("T") || getLetter().equals("S") ||
getLetter().equals("N") || getLetter().equals("N"))
value = "1";
is there a better way to do it?
Three options:
Use a switch statement, assuming you're using Java 7 or 8:
switch (getLetter()) {
case "A":
case "O":
case "I":
case "B":
...
value = "1";
...
}
Use three Set<String>
objects
Map<String, String>
The last option would be something like:
// You'd presumably initialize this in one place...
Map<String, String> map = new HashMap();
map.put("A", "1");
map.put("O", "1");
map.put("I", "1");
...
map.put("C", "5");
map.put("D", "5");
...
String value = map.get(getLetter());
See more on this question at Stackoverflow