Skip to content
Advertisement

What would be the most concise way to write below snippet in Java? [closed]

val dbPort = props["mysqlPort"]?.get(0)?.toInt() ?: 3306

props is Map<String, List>

currently am writing it this way:

var portStr = props.get("mysqlPort").get(0);
var dbPort = (portStr == null) ? 3306 : Integer.parseInt(portStr);

is this correct? can it be better?

Advertisement

Answer

Try this.

static int mySqlPort(Map<String, List<String>> prop) {
    return Optional.ofNullable(prop.get("mysqlPort"))
        .map(x -> x.get(0))
        .map(Integer::parseInt)
        .orElse(3306);
}

test case:

System.out.println("normal:         " + mySqlPort(Map.of("mysqlPort", Arrays.asList("1234", "4567"))));
System.out.println("null port:      " + mySqlPort(Map.of("mysqlPort", Arrays.asList(null, "4567"))));
System.out.println("no 'mysqlPort': " + mySqlPort(Map.of("sqlitePort", Arrays.asList("1234", "4567"))));

result:

normal:         1234
null port:      3306
no 'mysqlPort': 3306

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement