2

I have a database where I retrieve data from and store it in a Map<String, Any> collection.

It looks something like this when printed in a Log:

{-MxY_3dqegF7YmP-NEaE8={Factors={Percentage=52.89, Got Stuff=0, Happy=1}, Result=Ok, Probability=50}}

This looks fine, in Python I would know how to go about it as it would be like a dictionary, but the problem is the inner keys and values are of this Any type object in Kotlin.

I am unable to work with that type and iterate through the keys and lists. I can only print the data as a String but that's all I know:

    val values = snapshot.getValue<Map<String, Any>>()
    Log.d("[CLIENT]", "Value is: $values")
    
    var keys = mutableListOf<String>()
    var data = mutableListOf<Any>()
    
    if (values != null) {
        for ((k, v) in values) {
            keys.add(k)
        }
    }
    
    val check = values?.get(keys[0])
    Log.d("[CLIENT]", "Key is: $check")

It would print check like this:

{Factors={Percentage=52.89, Got Stuff=0, Happy=1}, Result=Ok, Probability=50}

check is of type Any?, so how do I convert it or use it like a Map, or any other simpler way, similar to like maybe Python Dictionaries?

3 Answers 3

4

Answering your question title of converting a Map<String, Any> to a Map<String, String>:

val values = hashMapOf<String, Any>("Foo" to 7, "Bar" to true)
val casted = values.map { e -> e.key to e.value.toString() }.toMap()

Although I don't think that's what you want, since you seem to have a Map<String, Map<String, Any>>.

Sign up to request clarification or add additional context in comments.

Comments

3

values.mapValues { it.values.toString() }

Returns a new map with entries having the keys of this map and the values obtained by applying the transform function to each entry in this Map.

Reference: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-values.html

Comments

0

Figured it out, simple type casting. Apologies, new to the language.

val check = values?.get(keys[0]) as Map<String, String>

The only issue here is a warning that says it is an Unchecked cast, but I have yet to figure out how to do it safely, please let me know if you do. For now it works as I know the data types.

This also works without warnings, as recommended by the IDE:

val check = values?.get(keys[0]) as Map<*, *>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.