Home > other >  Convert Map<String, Any> to Map<String, String> in Kotlin?
Convert Map<String, Any> to Map<String, String> in Kotlin?

Time:03-05

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?

CodePudding user response:

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<*, *>

CodePudding user response:

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>>.

  • Related