https://kotlinlang.org logo
Title
c

chansek

01/28/2022, 6:19 AM
How can I evaluate both of these in a single operator chain?
val adminOf = user.roles
    .filter { it.isAdmin() }
    .map { it.entityId to it.entity }
    .toMap()
val serviceProviderOf = user.roles
    .filter { it.isServiceProvider() }
    .map { it.entityId to it.entity }
    .toMap()
j

Joffrey

01/28/2022, 8:24 AM
Are admins and service providers the only 2 options? Are they mutually exclusive? You might be able to use
partition
instead of
filter
if the answer is yes
m

Matteo Mirk

01/28/2022, 12:06 PM
.map { it.entityId to it.entity }
    .toMap()
can be simplified to
.associate { it.entityId to it.entity }
e

ephemient

01/28/2022, 12:40 PM
or
.associateBy(
    keySelector = { it.entityId },
    valueTransform = { it.entity }
)
which doesn't require building a Pair and whose lambdas could be replaced with bound references (e.g.
User::entityId
etc.), but that's not really the important part of the question…
partition can work if they're exclusive (no user is in both) but if there's potential overlap, you're not gonna get something much clearer. you could update two mutable maps from a single for loop, whether that's better or not, depends…