有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果键存在且值不为null,则java放入映射,否则抛出异常

void addToMapIfKeyExists(String k, String v) {
    if (!map.containsKey(k)) {
        throw new NoSuchElementException(k + " does not exist in the map");
    }

    // else ignore
    if (v != null) {
        map.put(k, v);
    }
}

我能用Java 8更好地编写这个吗?我可以用某种方式把它合并成一个表达式吗


共 (1) 个答案

  1. # 1 楼答案

    记住,要求是:

    Put in the map if key exists or value is not null, else throw exception

    也就是说:

    • 如果密钥不存在,抛出异常
    • 如果值为null,则抛出异常
    • 把地图放进去

    您应该首先执行空检查,然后使用^{}方法并检查返回值,因此只执行一次映射查找

    void addToMapIfKeyExists(String k, String v) {
        if (v == null)
            throw new IllegalArgumentException("Value is null");
        if (map.replace(k, v) == null)
            throw new NoSuchElementException("Key doesn't exist: " + k);
    }