Morozov
Morozov

Reputation: 5250

How to group by HashMap?

I have next variable:

private var consents: Map<ConnectionID, List<ConsentData>> = emptyMap()

And after in my function i do next actions:

fun processDecryptedConsentsResult(result: List<ConsentData>) {
        this.consents = result.groupBy { it.connectionId ?: "" }
        ...
}

And everything works ok.

But now i changed my variable to:

private var consents: HashMap<ConnectionID, List<ConsentData>> = HashMap<ConnectionID, List<ConsentData>>()

And can't groupBy, because

Required: collections HashMap<ConnectionID /*=String*/, List<ConsentData>>
Found: Map<String. List<ConsentData>>

How i can groupBy my HashMap now?

Upvotes: 1

Views: 502

Answers (1)

Madhu Bhat
Madhu Bhat

Reputation: 15213

Since groupBy returns a Map<K, List<T>>, you cannot directly assign that to a HashMap field/property.

You can however initialize the HashMap by passing the Map as below:

this.consents = HashMap(result.groupBy { it.connectionId ?: "" })

Upvotes: 2

Related Questions