Java 三元运算符的错误

Java 三元运算符的错误,java,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

在以下代码中:

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);
}
有人知道如何解决这个问题吗?

将其改写为

leavesCount.put(leaf, leavesCount.containsKey(leaf) ? (leavesCount.get(leaf) + count) : count)
您应该替换LeaveScont.ContainesKeyLeaf吗?leaveScont.putleaf,leaveScont.getleaf+计数:leaveScont.putleaf,计数;与


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

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

在Java 8中,有一个优雅的内置方法来实现您想要的功能:

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

public void addLeaf(int leaf, int count) {
    leavesCount.merge(leaf, count, Integer::sum);
}
这将使用方法,该方法需要键和值,以及一个合并函数,如果映射中已经存在键,则该函数将旧值与新值合并


对于merge函数,我使用Integer::sum,它是Integer.sum方法的方法引用。此方法引用的行为类似于a,即它需要两个值并返回它们的和。

您没有将结果赋给任何对象。您必须使用if语句,三元运算符仅用作表达式。您确定在这段代码中出现此错误吗?你的代码应该会产生不同的错误。第二条建议让你得到了我的支持。这不是使用三元运算符的地方。
public void addLeaf(int leaf, int count){
    count = leavesCount.containsKey(leaf) ? leavesCount.get(leaf) + count : count;
    leavesCount.put( leaf, count)
}
public Map<Integer, Integer> leavesCount = new HashMap<>();

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