三元运算符出错

时间:2017-07-19 16:30:07

标签: java

在以下代码中:

public Map<Integer, Integer> leavesCount = new HashMap<Integer, Integer>();

public void addLeaf(int leaf, int count){
    leavesCount.containsKey(leaf) ? leavesCount.put(leaf, leavesCount.get(leaf) + count) : leavesCount.put(leaf, count);
}

我在leaf

中的containsKey出现以下错误
Type mismatch: cannot convert from int to boolean

有谁知道如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

将其重写为

leavesCount.put(leaf, leavesCount.containsKey(leaf) ? (leavesCount.get(leaf) + count) : count)

答案 1 :(得分:1)

这不是三元运作的工作方式。要使用三元组,您需要将函数更改为

public void addLeaf(int leaf, int count){
    leavesCount.put( leaf, leavesCount.containsKey(leaf) ? leavesCount.get(leaf) + count : count)
}

这不是最好的做法。你最好使用if语句。

public void addLeaf(int leaf, int count){
    if(leavesCount.containsKey(leaf)){
        leavesCount.put(leaf, leavesCount.get(leaf) + count);
    }else{
        leavesCount.put(leaf, count);
    }
}

原因是可读性。将三元组置于函数调用内部可能会变得混乱。

您也可以将其移至var。

public void addLeaf(int leaf, int count){
    count = leavesCount.containsKey(leaf) ? leavesCount.get(leaf) + count : count;
    leavesCount.put( leaf, count)
}

答案 2 :(得分:1)

在Java 8中,有一种优雅的内置方法可以做你想做的事情:

public Map<Integer, Integer> leavesCount = new HashMap<>();

public void addLeaf(int leaf, int count) {
    leavesCount.merge(leaf, count, Integer::sum);
}

这使用Map.merge方法,它需要键和值,以及合并函数,如果键已经存在于地图中,它将旧值与新值合并

对于合并功能,我使用Integer::sum,这是Integer.sum方法的方法参考。此方法引用的行为类似于BiFunction<Integer, Integer, Integer>,即它需要两个值并返回它们的总和。

答案 3 :(得分:0)

您应该将leavesCount.containsKey(leaf) ? leavesCount.put(leaf, leavesCount.get(leaf) + count) : leavesCount.put(leaf, count);替换为

    if (leavesCount.containsKey(leaf)) {
        leavesCount.put(leaf, leavesCount.get(leaf) + count);
    } else {
        leavesCount.put(leaf, count);
    }