Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin: How convert from Set to Map?

I have Set<FlagFilter> and I need to convert it to Map<Class<out FlagFilter>, FlagFilter>.

I tried doing it like this:

val result: Map<Class<out FlagFilter>, FlagFilter> =
     target
        .takeIf { !it.isEmpty() }
         ?.map { mapOf(it.javaClass to it) }
         ?: emptyMap<>()

but instead of a Map it turns out to be a List and I get a compilation error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type mismatch.
Required: Map<Class<out FlagFilter>, FlagFilter>
Found: List<Map<Class<FlagFilter>, FlagFilter>>

What am I doing wrong? As if there is not enough operation, but I do not understand yet which one

>Solution :

Just use associateBy extension function:

val result: Map<Class<out FlagFilter>, FlagFilter> =
    target.associateBy { it.javaClass }

Or if you want to fix your code, remove the excessive call of mapOf(). Just convert your Set to List of Pairs, and then call toMap() to create a map:

val result: Map<Class<out FlagFilter>, FlagFilter> =
    target.map { it.javaClass to it }.toMap()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading