Problem Statement
Explain the associate, associateBy, and associateWith functions for creating Maps from collections.
Explanation
Associate creates a Map by transforming each element into a Pair of key and value using a lambda that returns key to value pairs, giving full control over both keys and values. AssociateBy uses elements as values and derives keys from a lambda, while associateWith uses elements as keys and derives values from a lambda.
Use associate when you need to transform elements into completely different keys and values, associateBy to create a lookup map where you keep original elements as values with custom keys, and associateWith to create maps where elements are keys with computed values.
Examples: people dot associateBy curly it dot id curly creates ID to person map, numbers dot associateWith curly it times it curly creates number to square map, and associate with key to value pairs for full transformation.
These functions handle duplicate keys by keeping the last occurrence, and you can use groupBy instead if you need to keep all elements with the same key. Understanding these associate functions helps avoid manual map building loops.
Practice Sets
This question appears in the following practice sets:
