LivBanana
LivBanana

Reputation: 381

Is there an alternative to `groupBy` for this case?

I have a map of items, the keys are item identifiers and the values are Item objects.

Each Item object have properties such that id (a string identifier) and container (the container to which it belongs). A Container is also an object it has many properties but here only the id is needed.

I want to get the list of all containers identifiers (without repetition)

val containersIds : Set<String> = items.values.groupBy { item -> items.getValue(item.id).container.id }.keys

It does the job but maybe there is something else than using groupBy and keys.

Any ideas ?

Upvotes: 1

Views: 85

Answers (1)

cactustictacs
cactustictacs

Reputation: 19562

You just want the ID of each item's container, with no duplicates?

items.values().map { it.container.id }.distinct()

Or since you want a Set anyway, you get the uniqueness for free!

items.values().map { it.container.id }.toSet()

Or skip the values list and just work on the entries

items.map { (_, item) -> item.container.id }.toSet()

Upvotes: 2

Related Questions