Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make a Java map like this JS example?

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]
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
    };
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading