我有一个整数字符串的映射。我想检查地图是否有某个字符串,如果是,请修改它映射到的整数值。
Map <String, Integer> m= new SortedMap <String,Integer>();
Map <String, Integer> m2 = new SortedMap<StringInteger>();
//do some stuff
Iterator <String,Integer> i = m2.iterator();
//add some values into the first map first map
while (i.hasNext()){
String temp = i.next();
int found = m.get(temp);
if ( found != null) {//this is giving me a syntax error , something about how ints
can't be null , do I just compare it to zero
//process value that temp maps to
averages.put(temp, val); //
}
}
当我在第二个循环中输入密钥时,它会删除第一个密钥,并使用新的过程值输入另一个密钥。
答案 0 :(得分:5)
您需要将int
更改为Integer
:
Integer found = m.get(temp);
'int'是一个原语,不能与null比较。
地图键是唯一的,因此如果您将相同的键放两次,它将被替换
答案 1 :(得分:2)
看起来你要做的事情可以用putAll完成。
Map<String, Integer> both = ...
both.putAll(m1);
both.putAll(m2);
这将包含m2中的所有值以及仅m1中的任何值。
答案 2 :(得分:1)
通过引用可变自定义类添加这样的东西:
Map<String, MyValue> myMap = new HashMap<String, MyValue>();
(...)
MyValue value = myMap.get(temp);
value.inc();
(...)
public class MyValue {
private int value;
public int get() {
return value;
}
public void set(int newValue) {
this.value = newValue;
}
public void inc() {
value++;
}
}
编辑:使用上述方法填写所有值:
for(MyValue value : myMap.values()) {
value.inc();
}
没有MyValue包装器:
for(String key : m.keySet()) {
Integer value = m.get(key);
m.put(key, value + 1);
}