How can I evaluate both of these in a single opera...
# codereview
c
How can I evaluate both of these in a single operator chain?
Copy code
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
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
Copy code
.map { it.entityId to it.entity }
    .toMap()
can be simplified to
Copy code
.associate { it.entityId to it.entity }
e
or
Copy code
.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…