JAVA - HashMap检查特定的键值(如果更大)
Map<Integer, Integer> listInfo = new HashMap<Integer, Integer>();
我一直在试图从谷歌搜索,但我不知道为什么我找不到正确的解决方案。无论如何,我的HashMap将存储两个整数。我会使用普通的“int []”字符串列表或任何它被调用,但它会返回异常的事情有关“数组outofbounds”或相关的东西,因为它的索引将比int大。不确定,但无论如何,让我们留在话题中。JAVA - HashMap检查特定的键值(如果更大)
我的英语很糟糕,但如果你不明白我在说什么,希望这会有所帮助。 (只是想法,不是基于真正的代码)
if(listInfo.containsKey(key)) {
if(listInfo.getKeyValue(key).valueOfKey() > valueToBeAdded) {
listInfo.put(key, valueToBeAdded);
}
} else {
listInfo.put(key, valueToBeAdded);
}
我都试过比上述类似的方式,但非常正确的功能,但它会产生冲突,因为它说,它不能比较键值int,因为键值是对象吗?为什么它是对象,因为我已经定义它应该是整数?我也尝试过(Entry entry:......)循环,但我不知道如何获得特定键的值(我不是在谈论键值,我正在谈论的是特定键的值持有)
我只想更新特定(现有)键所保持的值,如果该键所保存的值较大并且要添加的值小于当前值。
在下面找到一个你正在寻找的代码片段(假设我理解你的意图)。
Map<Integer, Integer> listInfo = new HashMap<>();
listInfo.put(1, 23);
listInfo.put(2, 45);
Integer valueToBeAdded = 42;
System.out.println("listInfo = " + listInfo);
if (listInfo.containsKey(1)) {
if (listInfo.get(1) < valueToBeAdded) {
listInfo.put(1, valueToBeAdded);
}
} else {
listInfo.put(1, valueToBeAdded);
}
System.out.println("listInfo = " + listInfo);
输出
listInfo = {1=23, 2=45} // the initial listInfo entries (key, value)
listInfo = {1=42, 2=45} // after the value for key `1` has been updated
我刚刚要添加代码,但在此之前必须做更多的调试,但实际上在第6-9行获得了解决方案。我不认真了解是什么导致了这个错误,因为我在发布后立即清理了太多的代码。但工作得很好O_o我很头疼。谢谢。 –
看起来你只想把那个较小值。
为此,您可以使用Map.compute
:
final HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
map.put(123, 456);
System.out.println(map);
final int x = 234;
final BiFunction<? super Integer, ? super Integer, ? extends Integer> f =
(k, v) -> v == null ? x : Math.min(v, x);
map.compute(123, f);
map.compute(999, f);
System.out.println(map);
可悲的是,Java不支持真正的函数式编程。有一个简单的部分应用程序将是很好的。 这是一个静态方法的版本,部分应用某个值并返回一个BiFunction
(f
是一个更高阶的函数)。
public static void main(final String[] arrg) {
final HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
map.put(123, 456);
System.out.println(map);
map.compute(123, f(345));
map.compute(123, f(99999));
map.compute(999, f(888));
System.out.println(map);
}
static BiFunction<? super Integer, ? super Integer, ? extends Integer> f(final int x) {
return (k, v) -> v == null ? x : Math.min(v, x);
}
向我们展示您的代码,我们无法猜测您做错了什么。 – Shadov
和确切的错误。请[编辑]问题,并粘贴代码和错误。不要忘记用'{}'按钮来设置它们的格式。 – RealSkeptic
瞬间。我会添加它。 –