Weird E. Weird E. - 2 months ago 6
Java Question

JAVA - HashMap check specific key value (if greater)

Map<Integer, Integer> listInfo = new HashMap<Integer, Integer>();


I have been trying to search from Google, but I don't really know why I cannot find a correct solution. Anyways my HashMap will store two Integers. I would use normal "int[]" string-list or whatever it is called for, but it will return me exception something about "array outofbounds" or something related to that, because it's index will be greater than int. Not sure, but anyways let's stay in the topic.

My english is pretty bad, but if you don't understand what I'm talking about hope this helps. (Just the idea, not based in real code)

if(listInfo.containsKey(key)) {
if(listInfo.getKeyValue(key).valueOfKey() > valueToBeAdded) {
listInfo.put(key, valueToBeAdded);
}
} else {
listInfo.put(key, valueToBeAdded);
}


I have tried similar way than above, but with pretty much correct functions, but it will conflict, because it says that it cannot compare key value with int, because key value is object? Why it's object, because I've defined that it should be Integer? I've also tried for(Entry entry : ......) loop, but I have no clue how I can get specific key's value (I am not talking about key value, I'm talking about value that the specific key holds)

I want only update the value that the specific (existing) key holds if the value that key holds is greater and the value that will be added is less than the current one.

Answer

Find below a snippet which does what you are looking for (assuming that I right understood your intention).

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

output

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
Comments