I have started lately learning Java. I can’t figure out how to write something like this in Java.
This is how would I have done it in JS.
function getColorCode(color){
var colorCodes = {
'black' : '\u00A70',
'dark_blue' : '\u00A71',
'dark_green' : '\u00A72'
}
return colorCodes[color]
}
>Solution :
A direct translation of your function to Java would be:
public String getColorCode(String color) {
var colorCodes = Map.of(
"black", "\u00A70",
"dark_blue", "\u00A71",
"dark_green", "\u00A72");
return colorCodes.get(color);
}
However, it would be better to define the map once, instead of on each invocation:
private static final Map<String, String> COLOR_CODES = Map.of(
"black", "\u00A70",
"dark_blue", "\u00A71",
"dark_green", "\u00A72");
public String getColorCode(String color) {
return COLOR_CODES.get(color);
}
Or use a switch expression:
public String getColorCode(String color) {
return switch (color) {
case "black" -> "\u00A70";
case "dark_blue" -> "\u00A71";
case "dark_green" -> "\u00A72";
default -> null;
};
}