In the following code:
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);
}
I get the following error with leaf
inside the containsKey
:
Type mismatch: cannot convert from int to boolean
Does anyone know how to solve the issue?
重写为
leavesCount.put(leaf, leavesCount.containsKey(leaf) ? (leavesCount.get(leaf) + count) : count)
That's not how ternary operations work. To use a ternary for this you would want to change the function to
public void addLeaf(int leaf, int count){
leavesCount.put( leaf, leavesCount.containsKey(leaf) ? leavesCount.get(leaf) + count : count)
}
Which isn't really best practice. You are better off using an if statement.
public void addLeaf(int leaf, int count){
if(leavesCount.containsKey(leaf)){
leavesCount.put(leaf, leavesCount.get(leaf) + count);
}else{
leavesCount.put(leaf, count);
}
}
The reason for this is readability. Putting a ternary inside of a function calls can start to get messy.
You could also move it to a var.
public void addLeaf(int leaf, int count){
count = leavesCount.containsKey(leaf) ? leavesCount.get(leaf) + count : count;
leavesCount.put( leaf, count)
}
In Java 8, there's an elegant built-in method to do what you want:
public Map<Integer, Integer> leavesCount = new HashMap<>();
public void addLeaf(int leaf, int count) {
leavesCount.merge(leaf, count, Integer::sum);
}
This uses Map.merge
method, which expects the key and the value, along with a merge function that merges the old value with the new value if the key was already present in the map.
For the merge function, I'm using Integer::sum
, which is a method reference to the Integer.sum
method. This method reference acts like a BiFunction<Integer, Integer, Integer>
, ie it expects two values and returns their sum.
You should replace leavesCount.containsKey(leaf) ? leavesCount.put(leaf, leavesCount.get(leaf) + count) : leavesCount.put(leaf, count);
leavesCount.containsKey(leaf) ? leavesCount.put(leaf, leavesCount.get(leaf) + count) : leavesCount.put(leaf, count);
with
if (leavesCount.containsKey(leaf)) {
leavesCount.put(leaf, leavesCount.get(leaf) + count);
} else {
leavesCount.put(leaf, count);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.