Map

From Elixir Wiki
Jump to navigation Jump to search

Map[edit]

The **Map** module in Elixir provides a collection of functions for working with maps. A map is a key-value store where keys can be any value, and values can be of any type. It is similar to a dictionary or hash table in other programming languages. Maps are often used to represent structured data, such as JSON objects or records.

Creating Maps[edit]

To create a new map, you can use the `%{}` syntax or the `Map.new/0` function. Here are some examples:

Example 1: Creating a map using `%{}` syntax ```elixir map = %{name: "John", age: 30, city: "New York"} ```

Example 2: Creating a map using `Map.new/0` ```elixir map = Map.new() ```

Accessing Map Elements[edit]

You can access individual elements in a map using the dot notation or the `Map.get/2` function. Here are some examples:

Example 1: Accessing a map element using dot notation ```elixir name = map.name ```

Example 2: Accessing a map element using `Map.get/2` ```elixir name = Map.get(map, :name) ```

Updating Maps[edit]

To update a map, you can use the `%{}` syntax or the `Map.put/3` function. Here are some examples:

Example 1: Updating a map using `%{}` syntax ```elixir updated_map = %{map | age: 31, city: "San Francisco"} ```

Example 2: Updating a map using `Map.put/3` ```elixir updated_map = Map.put(map, :age, 31) ```

Deleting Map Elements[edit]

To remove an element from a map, you can use the `Map.delete/2` function. Here is an example:

Example: Deleting a map element ```elixir updated_map = Map.delete(map, :city) ```

Map Functions[edit]

Elixir provides several useful functions for working with maps. Here are some common ones:

- `Map.merge/2`: Merges two maps together. - `Map.keys/1`: Returns a list of keys from a map. - `Map.values/1`: Returns a list of values from a map. - `Map.has_key?/2`: Checks if a map contains a specific key. - `Map.size/1`: Returns the number of key-value pairs in a map. - `Map.to_list/1`: Converts a map to a list of tuples.

For more information on these functions, please refer to the corresponding articles on this wiki.

Pattern Matching with Maps[edit]

One of the powerful features of Elixir is pattern matching. This extends to working with maps as well. You can use pattern matching to match specific keys and values in a map. Here is an example:

Example: Pattern matching with maps ```elixir %{name: name, age: age} = map ```

In this example, the variables `name` and `age` will be bound to the corresponding values in the map.

Conclusion[edit]

The Map module in Elixir provides a flexible and efficient way to work with key-value data. Whether you need to create, access, update, or delete elements in a map, Elixir has you covered. With the variety of functions available, you can manipulate and transform maps to suit your specific needs.

For more information on the Map module and other related topics, please explore the articles on this wiki.