Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all Map keys

Tags:

elixir

Is there a way in elixir to get all of the map keys similar to array_keys in PHP? I have been searching but cannot seem to find a way.

Or is there another way to get unique values? I am assigning names to keys in the map with a value of 1 to get only distinct values. Then I would like to get the keys to only retrieve the unique values.

I am using this code to create my map:

names = Enum.reduce lines, %{}, fn line, acc ->
  Map.put(acc, line.name, 1)
end

For example, I have two lines with line.name as test. I would want the end result to return just test. Or if they are different return them separately, then use something like enum.join to combine them

Enum.join(names, " - ")
like image 536
Michael St Clair Avatar asked Apr 03 '17 22:04

Michael St Clair


People also ask

How to get keys in map in Java?

The sample code below demonstrate how to get keys in map, whether its a hashmap or any implementation of Map. The method in Map that will get keys is: keySet(); This method will return a Set of object T where T is the type of object you have define to be the Keys when you initiliaze the Map.

What is the keys () method in map ()?

The keys () method returns a new Iterator object that contains the keys for each element in the Map object in insertion order. A new Map iterator object.

How do I get the key-value pair of a map?

Thus, in most cases, you'll want to get the key-value pair together. The entrySet () method returns a set of Map.Entry<K, V> objects that reside in the map. You can easily iterate over this set to get the keys and their associated values from a map.

How to retrieve all keys from a map in C++?

We can write custom logic for retrieving all keys from the map. The idea is to iterate over the map using a range-based for loop or iterator-based for-loop and insert each key into a container. Starting with C++17, we can use the range-based for-loop with structured bindings: 2. Using BOOST_FOREACH


1 Answers

You can use Map.keys/1:

map = %{a: 1, b: 2}
Map.keys(map)
#=> [:a, :b]
like image 179
Sheharyar Avatar answered Sep 21 '22 15:09

Sheharyar