Correctly returning Int from Hashmap in a function

how to get values from hashmap in java example
iterate through hashmap java
sort hashmap by value
hashmap methods
hashmap get
hashset
hashmap entryset
how to get all values from hashmap in java

I have a function in Kotlin which takes in an Int argument and return a value based on a formula. To speed things up I store intermediate results in a HashMap<Int, Int>

private val calculatedResults = HashMap<Int, Int>()

private fun q2(n: Int): Int {
    if(calculatedResults.containsKey(n)) {
            return calculatedResults[n]
    }

    val q = ...
    calculatedResults[n] = q
    return q
}

I'm getting a type mismatch of Int found but Int? required at

return calculatedResults[n]

Im not sure how to correctly write this. I had

return calculatedResults[n]!!

But I'm not sure, if it's a bit hacky.

Should the return type of the function be Int? because while the HashMap might contain the key n the value could be null? Wouldn't that mean the HashMap should be <Int, Int?>?

The underlying problem is that calculatedResults could have been modified by an other thread between contains (if(calculatedResults.containsKey(n))) and get (return calculatedResults[n]).

Even after checking with containsKey calculatedResults[n] could therefore possibly return a wrong result, including null, and this way of checking should be avoided.

Using !! should generally only be used when absolutely necessary, because it can cause a NPE. It definitely is hacky.

Use the following syntax to overcome the problem:

calculatedResults[n]?.let {
    return it
}

Basically this is a nice way of saying

val result = calculatedResults[n]
if(result != null) {
    return result
}

see https://kotlinlang.org/docs/reference/null-safety.html#safe-calls

Even better is to use the built-in getOrPut:

private fun q2(n: Int): Int {
    return calculatedResults.getOrPut(n) { calcQ() }
}

private fun calcQ(): Int {
    val q = ...
    return q
}

Should the return type of the function be Int? because while the HashMap might contain the key n the value could be null? Wouldn't that mean the HashMap should be <Int, Int?>?

No, you did exactly the right thing when you defined the method signature. The compiler only complained because what happened within the method did not fit it. If you change the method signature you just move the problem to the function calling q2 without handling it.

HashMap and int as key, What is the return type of put method in HashMap? You need to handle the initial state of there not being money in your hashmap, and return 0 there. Otherwise addMoedas will fail, because it calls getMoedas to get the previous value, which would throw an NPE.

getOrPut will check if a value exists for n. If the value exists, it will be returned. If the values does not exist the value returned by the lambda will be assigned and afterwards returned by getOrPut.

Take a look at this example:

fun calculate(n: Int) = n * 5 // some calculation

private fun q2(n: Int) = calculatedResults.getOrPut(n) {
    calculate(n)
}

Should the return type of the function be Int? because while the HashMap might contain the key n the value could be null? Wouldn't that mean the HashMap should be ?

In this case the answer to the question is obviously "no" because if the value is missing you just add it. So, the value returned by q2 can never be null.

Return Value of put() in HashMap, , as I did above, because it's considered a best practice to always program to an interface rather than a concrete class. Map<String, Integer> myMap = new HashMap<String, Integer>(); With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write: myMap.put("foo", 3); instead of: myMap.put("foo", new Integer(3)); Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:

You should consider re-writing this to more idiomatic code. It's a rather basic task to compute a value if it is not set in the map already:

fun q2(n: Int): Int {
    return calculatedResults.getOrPut(n) {
        42 //q
    }
}

Is it possible to return a HashMap object in Java?, the values of the map. It basically returns a Collection view of the values in the HashMap. Program 1: Mapping String Values to Integer Keys. filter_none. edit HashMap provides constant time complexity for basic operations, get and put if the hash function is properly written and it disperses the elements properly among the buckets. Iteration over HashMap depends on the capacity of HashMap and a number of key-value pairs.

HashMap in Java with Example, Return Value: This method returns the previous value associated with the specified key. If there is no such add some values. HashMap<String, Integer> map. The merge(Key, Value, BiFunctional) method of HashMap class is used to combine multiple mapped values for a key using the given mapping function. Bucket is actually an index of array, that array is called table in HashMap implementation.

HashMap values() Method in Java, Java HashMap in a collection class which implements Map interface. elements are iterated in the linkedlist and correct value object is found by identifying the correct key using it's equals() method. HashMap<Integer, String> map = new HashMap<>(); Set keySet() : returns the Set of the all keys stored in the HashMap. java.util.HashMap.get() Method - The get(Object key) method is used to return the value to which the specified key is mapped, or null if this map contains no mapping

HashMap replace(key, value) method in Java with Examples , put), assuming the the hash function disperses the elements properly among the buckets. synchronizedMap method. Returns true if this HashMap maps one or more keys to the specified value. Removes the mapping for this key from this HashMap if present. int, size() Returns the number of key-value mappings inĀ  A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.